我是一名新手php程序员。我一直在尝试通过替换扩展名来重命名文件夹中的所有文件。
我正在使用的代码来自SO上类似问题的答案。
if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($fileName, $newName);
}
closedir($handle);
运行代码时没有出现错误,但文件名没有发生任何变化。
为什么会这样呢?我的权限设置应该是允许的。
提前感谢您的帮助。
编辑:使用rename()函数进行检查返回值时得到了一个空白页面,现在正在尝试使用glob()函数,它可能比opendir更好?
第2次编辑:使用下面的第二段代码,我可以打印$newfiles的内容。所以数组是存在的,但str_replace + rename()代码片段无法更改文件名。
$files = glob('testfolder/*');
foreach($files as $newfiles)
{
//This code doesn't work:
$change = str_replace('php','html',$newfiles);
rename($newfiles,$change);
// But printing $newfiles works fine
print_r($newfiles);
}