PHP - 将文件夹中的所有文件重命名为 1.ext、2.ext、3.ext


PHP - Rename all files in folder to 1.ext, 2.ext, 3.ext

...当然,对于 .ext,我的意思是,保留原始扩展名!

现在这个问题以前有人问过,但奇怪的是,答案甚至远程不起作用。对我来说,就是这样。

现在,我从这个开始:

$directory = $_SERVER['DOCUMENT_ROOT'].$fileFolder.'/';
$i = 1; 
$handler = opendir($directory);
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        $newName = $i . '.jpg';
        rename($file, $newName);
        $i++;
    }
}
closedir($handler);

对我来说似乎很简单,但它不会重命名任何文件......有谁知道出了什么问题?或者只是一个工作片段... :D

重命名

时需要完整的相对/绝对名称,而不是相对于当前正在浏览的目录的文件名。但readdir()仅返回相对于您正在浏览的目录的文件名。

$directory = $_SERVER['DOCUMENT_ROOT'].$fileFolder.'/';
$i = 1; 
$handler = opendir($directory);
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        $newName = $i . '.jpg';
        rename($directory.$file, $directory.$newName); // here; prepended a $directory
        $i++;
    }
}
closedir($handler);

readdir()仅返回您正在扫描的目录的文件名。由于您打开了运行脚本的任何目录的子目录,因此您需要在重命名调用中包含该子目录,例如:

    rename($directory . $file, $directory . $newName);
<?
$dir = opendir('test');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
    // if the extension is '.jpg'
    if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
    {
        // do the rename based on the current iteration
        $newName = 'test/'. $i . '.jpg';
        $new = 'test/'.$file;
        rename($new, $newName);
        // increase for the next loop
        $i++;
    }
}
// close the directory handle
closedir($dir);
?>
www.codeprojectdownload.com