php 在php中重命名文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13434883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:25:53  来源:igfitidea点击:

rename file in php

php

提问by DolDurma

I want to rename picturefilename (without extension) to old.jpgfrom this code.

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

I have picturefile in parent directory and the path is correctly

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

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

or this codes

或者这个代码

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

But I get this error:

但我收到此错误:

 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

采纳答案by Ja?ck

A relative path is based on the script that's being executed ($_SERVER['SCRIPT_FILENAME']when run in web server) which is not always the file in which the file operation takes place:

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

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

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

Finding a relative path involves comparing the absolute paths of both the executing script and the file you wish to operate on, e.g.:

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

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

In this example, the relative path is: ../images/picture

在这个例子中,相对路径是: ../images/picture

回答by Peter Krejci

You need to use either absolute or relative path (maybe better in that case). If it's in the parent directory, try this code:

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

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

回答by Wes Foster

Like Seth and Hyman mentioned, the error is appearing because the script cannot find the old file. You're making it look in the current directory and not it's parent.

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

To fix this, either enter the full path of the old file, or try this:

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

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

The ../traverses up a single directory, in this case, the parent directory. Using ../works in windows as well, no need to use a backslash.

../穿越了一个目录,在这种情况下,父目录。使用../Windows中的作品为好,没有必要用一个反斜杠。

If you are still getting an error after making these changes, then you may want to post your directory structure so we can all look at it.

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