在 PHP 中重命名文件

12

我希望重命名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

3
你的路径明显不正确。 - Vultour
1
如果它在父目录中,您将使用'../picture'。 - Ja͢ck
2
@Jack输入反斜杠(\),他正在使用Windows操作系统。 - Vultour
4
在Windows系统上,@Seth /符号可以正常使用,但如果想要实现可移植性,建议使用DIRECTORY_SEPARATOR代替。 - Ja͢ck
4个回答

9

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

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

9

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

// 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

4

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

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

rename("../picture.jpg", "old.jpg");
../可以向上遍历一级目录,例如父级目录。在Windows中也可以使用../,不需要使用反斜杠。如果更改后仍然出现错误,则可以发布您的目录结构以供大家查看。

我不能也不想使用完整路径。在更改后,我遇到了错误。现在对我没有用。警告:rename(“../picture”,“old.jpg”)[function.rename]:系统找不到指定的文件。(代码:2)位于C:\xampp\htdocs\prj\change.php的第21行。 - DolDurma

0

可能你(即在发出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

参考资料:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接