使用PHP重命名文件夹中的所有文件

3

我是一名新手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);
}

可能是[批量重命名文件夹中的文件-PHP]的重复问题(https://dev59.com/dW445IYBdhLWcg3wLXWh)。 - G_real
5个回答

11

以下是简单的解决方案:

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文件。


7

您可能正在错误的目录中工作。请确保将$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);
}

嗨Telgin,谢谢你的回答。不幸的是,我尝试了一下,结果相同,代码没有生成错误,但也没有任何更改。 - Munner
@Munner 试着检查一下 rename 的返回值。如果无法重命名文件,它应该返回 false。这将有助于缩小问题范围。 - Telgin
代码运行良好,只需要进行一点微调:将以下代码放在白名单循环中以排除当前和父文件夹:if($fileName == "." || $fileName == "..") continue; - hlorand
对我没用。没有错误,但文件名也没有改变。 - Azamat

0
<?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);
}
?>

非常感谢您的建议。它对我很有帮助!

0

你确定吗?

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

0

如果文件已经被打开,那么 PHP 就无法对其进行任何更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接