【问题标题】:rename file in php在php中重命名文件
【发布时间】:2012-11-17 21:20:03
【问题描述】:

我想从此代码中将 picture 文件名(不带扩展名)重命名为 old.jpg

我在父目录中有picture文件并且路径是正确的

$old="picture";
$new="old.jpg";
rename($old , $new);

或此代码

$old="\picture";
$new="\old.jpg";
rename($old , $new);

$old="../picture";
$new="../old.jpg";
rename($old , $new);

$old="../picture";
$new="old.jpg";
rename($old , $new);

$old="./picture";
$new="./old.jpg";
rename($old , $new);

rename("picture", "old.jpg");

但我收到此错误:

 Warning: rename(picture,old.jpg) [function.rename]: The system cannot find the file specified. (code: 2) in C:\xampp\htdocs\prj\change.php on line 21

【问题讨论】:

  • 你的路径显然不正确
  • 如果它在父目录中你会使用'../picture'
  • @Jack 一个反斜杠 (\),他正在使用 windows
  • @Seth 正斜杠在 Windows 上工作得很好,但如果你想要便携,你会说 DIRECTORY_SEPARATOR

标签: php


【解决方案1】:

相对路径基于正在执行的脚本($_SERVER['SCRIPT_FILENAME'] 在 Web 服务器中运行时),它并不总是发生文件操作的文件:

// index.php
include('includes/mylib.php');

// mylib.php
rename('picture', 'img506.jpg'); // looks for 'picture' in ../

查找相对路径涉及比较执行脚本和您要操作的文件的绝对路径,例如:

/var/www/html/index.php
/var/www/images/picture

在本例中,相对路径为:../images/picture

【讨论】:

    【解决方案2】:

    您需要使用绝对路径或相对路径(在这种情况下可能会更好)。如果它在父目录中,请尝试以下代码:

    old = '..' . DIRECTORY_SEPARATOR . 'picture';
    $new = '..' . DIRECTORY_SEPARATOR . 'old.jpg';
    rename($old , $new);
    

    【讨论】:

      【解决方案3】:

      就像 Seth 和 Jack 提到的那样,出现错误是因为脚本找不到旧文件。你让它看起来在当前目录中,而不是它的父目录。

      要解决此问题,请输入旧文件的完整路径,或尝试以下操作:

      rename("../picture.jpg", "old.jpg");
      

      ../ 向上遍历单个目录,在本例中为父目录。使用../ 也可以在 Windows 中使用,无需使用反斜杠。

      如果您在进行这些更改后仍然收到错误,那么您可能需要发布您的目录结构,以便我们都可以查看它。

      【讨论】:

      • 我不能也不想使用完整路径。更改为多数民众赞成后我得到错误。现在不适合我。`警告:重命名(“../picture”,“old.jpg”)[function.rename]:系统找不到指定的文件。 (代码:2)在第 21 行的 C:\xampp\htdocs\prj\change.php 中`
      【解决方案4】:

      可能您(即发出rename() 命令时的脚本)不在您认为的目录中(和/或您的文件所在的位置)。要调试,首先显示目录中的文件列表:

        $d=@dir(".");// or experiment with other directories, e.g. "../files"
        while($e=$d->read()) { echo $e,"</br>"; }
      

      找到包含文件的目录后,您可以切换到该目录,然后在没有任何路径的情况下进行重命名:

        chdir("../files"); // for example
        // here you can print again the dir.contents for debugging as above
        rename( "picture", "img.jpg" ); // args are: $old, $new
        // here you can print again the dir.contents for debugging as above
      

      参考资料:

      【讨论】:

        猜你喜欢
        • 2014-09-09
        • 1970-01-01
        • 2014-01-20
        • 1970-01-01
        • 2012-03-06
        • 2019-03-23
        • 1970-01-01
        • 2015-01-11
        • 1970-01-01
        相关资源
        最近更新 更多