【问题标题】:After changing name of a file it goes parent directory更改文件名后进入父目录
【发布时间】:2021-08-24 13:52:38
【问题描述】:

我正在编写一个 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++;
    }
}    
?>

它可以工作,但最后,“图像”文件夹中的文件转到C:\wamp64\www\Replace image names with input directory。 (父目录)

知道为什么会这样吗?

【问题讨论】:

  • 不清楚您所说的“最终……”是什么意思?您是说它将所有图像保存到父文件夹中吗?或者是其他东西?请澄清一下,也许可以举个例子。
  • 看来,您为目标文件设置了相对路径。因此,它被移动到脚本运行的目录。设置完整路径
  • 是的@ADyson,他们去父文件夹

标签: php filenames glob txt


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    基于 splash58 的评论:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-22
        • 2015-02-11
        相关资源
        最近更新 更多