使用PHP重命名文件夹中的所有文件
新的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);
}
您可能正在错误的目录中工作。确保将$ fileName和$ newName加在目录前面。
尤其是,opendir和readdir不传达任何有关当前工作目录的信息以进行重命名。 readdir只返回文件的名称,而不是它的路径。所以你只传递文件名来重命名。
类似下面应该更好的工作:
$directory = '/public_html/testfolder/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
你肯定
opendir($directory)
的作品?你检查过了吗?因为它看起来可能有一些文档根在这里失踪......
我会尝试
$directory = $_SERVER['DOCUMENT_ROOT'].'public_html/testfolder/';
然后Telgin的解决方案:
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
非常感谢你的建议。到目前为止,我一直在尝试一系列的解决方案,但没有成功,我会尝试上面的修改并让您知道! – Munner 2012-08-15 16:33:15
下面是简单的解决方案:
PHP代码:
// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
$file = realpath($filename);
rename($file, str_replace(".html",".php",$file));
}
上面的代码将所有.html
文件转换在.php
,如果文件被打开情况。然后php不能对文件做任何改变。
<?php
$directory = '/var/www/html/myvetrx/media/mydoc/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$dd = explode('.', $fileName);
$ss = str_replace('_','-',$dd[0]);
$newfile = strtolower($ss.'.'.$dd[1]);
rename($directory . $fileName, $directory.$newfile);
}
closedir($handle);
}
?>
非常感谢您的建议。它为我工作!
嗨泰金,谢谢你的回答。不幸的是,我尝试了它,并得到相同的结果,代码不会产生错误,但不会有任何更改。 – Munner 2012-08-14 15:21:57
@Munner尝试检查重命名的返回值。如果它不能重命名文件,它应该返回false。这将有助于缩小问题的范围。 – Telgin 2012-08-14 15:28:17