Php 更改文件名后,它进入父目录

Php 更改文件名后,它进入父目录,php,filenames,glob,txt,Php,Filenames,Glob,Txt,我正在编写一个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

我正在编写一个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 to input directory
。(父目录)


知道为什么会这样吗?

根据splash58的评论:


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

使其更清晰。下面是您的代码正在执行的操作:

$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"

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


这对我来说很管用-重命名所有旧文件并用新命名文件替换它们。

不清楚“最终会变成…”是什么意思?你是说它会将所有图像保存到父文件夹中?还是别的什么?请澄清,并给出一个例子。看起来,您为目标文件设置了一个相对路径。因此,它被移动到脚本运行的目录。设置完整路径Yes@ADyson,它们将转到父文件夹