新的PHP程序员在这里.我一直试图通过替换扩展名来重命名文件夹中的所有文件.
我正在使用的代码是关于SO的类似问题的答案.
if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($fileName, $newName);
}
closedir($handle);
Run Code Online (Sandbox Code Playgroud)
}
运行代码时没有出现任何错误,但没有对文件名进行任何更改.
有关为什么这不起作用的任何见解?我的权限设置应该允许它.
提前致谢.
编辑:我在检查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);
}
Run Code Online (Sandbox Code Playgroud)