更改文件名后,它转到父目录

问题描述

我正在编写一个 PHP 代码,它从 input.txt 文件获取名称,并使用这些名称更改图像文件夹中文件名称

我的代码是:

<?PHP
$array = explode(".png",file_get_contents('input.txt'));

$directory='C:\wamp64\www\Replace image names with input\images';
$extension = '.png';
$a=0;
$newName='';

$dir = "images/*";

foreach(glob($dir) as $file)
{
    if(!is_dir($file)) {
        echo basename($file)."\n";
        $newName=$array[$a].".png";
        rename($file,$newName);
        $a++;
    }
}    
?>

它可以工作,但最后,'image' 文件夹中的文件变成了 C:\wamp64\www\Replace image names with input directory。 (父目录)

知道为什么会这样吗?

解决方法

为了更清楚。这是您的代码正在执行的操作:

$dir = "images/*";

foreach(glob($dir) as $file) {
// at this point $file === "images/filename"
    if(!is_dir($file)) {
        echo basename($file)."\n";
        $newName=$array[$a].".png";
// You set the $newName to newname.png
        rename($file,$newName);
// you replace "images/filename" with "newname.png"
        $a++;
    }
}

实际上,您已经编写了一个移动和重命名函数。为简单起见,您可以这样做:

$newName="images/".$array[$a].".png"
,

基于 splash58 的评论:

使用 scandir($directory) 而不是 glob($dir)

,

我完全理解你的担忧。我使用重命名功能尝试了您的代码并遇到了同样的问题。解决方案是提供包含要重命名和替换的图像的目录的绝对路径作为第二个参数。做这个: ... 重命名($file,"images/" . $newname); ...

这对我有用 - 用新命名的文件重命名并替换所有旧文件。