新的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)
这是简单的解决方案:
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));
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将转换所有.html文件.php
小智 5
你可能在错误的目录中工作.确保在目录中添加$ 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23317 次 |
| 最近记录: |