新的php程序员在这里。我一直试图通过替换扩展名来重命名文件夹中的所有文件。使用PHP重命名文件夹中的所有文件
我正在使用的代码是从the answer to a similar question on 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);
}
嗨泰金,谢谢你的回答。不幸的是,我尝试了它,并得到相同的结果,代码不会产生错误,但不会有任何更改。 – Munner 2012-08-14 15:21:57
@Munner尝试检查重命名的返回值。如果它不能重命名文件,它应该返回false。这将有助于缩小问题的范围。 – Telgin 2012-08-14 15:28:17