简体   繁体   English

移动文件并重命名

[英]Move a file and rename it

Figured PHP's rename would be my best bet. 想PHP的重命名将是我最好的选择。 I didn't see many examples on how to use relative URLs in it though, so I kind of compromised. 我没有看到很多关于如何在其中使用相对URL的示例,所以我有点妥协。 Either way, this give me permission denied: 无论哪种方式,这给了我许可否认:

I want to do this: 我想做这个:

$file = "../data.csv";
rename("$file", "../history/newname.csv");

Where ../ of course would go back 1 directory from where the script is being ran. 其中../当然会返回运行脚本的目录。 I couldn't figure out a way...so I did this instead: 我想不出办法......所以我这样做了:

$file = "data.csv";
$path = dirname(realpath("../".$file));
rename("$path/$file", "$path/history/newname.csv");

However I am getting permission denied (yes the history folder is owned by www-data, and yes data.csv is owned by www-data). 但是我被拒绝许可 (是的,历史文件夹由www-data拥有,是的,data.csv由www-data拥有)。 I thought it was weird so I tried a simple test: 我觉得这很奇怪所以我尝试了一个简单的测试:

rename( 'tempfile.txt', 'tempfile2.txt' );

and I made sure www-data had full control over tempfile.txt...still got permission denied. 我确保www-data完全控制tempfile.txt ...仍然被拒绝权限。 Why? 为什么? does the file your renaming it to have to exist? 你重命名它的文件必须存在吗? can you not rename like linux's mv? 你不能像linux的mv一样重命名吗? So I instead just copy() and unlink()? 所以我只是复制()和取消链接()?

In order to move a file from "../" to "../history/", a process needs write permission to both "../" and "../history/". 为了将文件从“../”移动到“../history/”,进程需要对“../”和“../history/”的写入权限。

In your example, you're obviously lacking write permission to "../". 在您的示例中,您显然缺少对“../”的写入权限。 Permissions for the file being moved are not relevant, by the way. 顺便说一下,正在移动的文件的权限是不相关的。

Not only ownership plays a role, but also file permissions. 所有权不仅起着作用,还起着文件权限的作用。 Make sure that the permissions are set up correctly on the source file and destination directory (eg chmod 644 data.csv ). 确保在源文件和目标目录上正确设置了权限(例如chmod 644 data.csv )。

Is www-data the same user as Apache? www-data与Apache的用户相同吗?

Edit: Take care to provide existing, absolute paths to realpath() . 编辑:注意提供realpath() 现有绝对路径 Also beware of the following: 还要注意以下事项:

$path = dirname(realpath("../".$file));

This might yield nothing, because the file ../data.csv might not exist. 这可能不会产生任何结果,因为文件../data.csv可能不存在。 Ie, the result of realpath() on a non-existent file is false . 即,不存在的文件上的realpath()的结果是false

Here's some code that might work better for you: 以下是一些可能更适合您的代码:

$file = "data.csv";
$path1 = realpath($file);
$path2 = realpath(dirname($file).'/..').'/history/newname.csv';
rename($path1, $path2);

You should be extremely careful that $file cannot be edited by the visitor, because he could change a request manipulate which file is renamed to where. 您应该非常小心访问者无法编辑$file ,因为他可以更改请求操作将哪个文件重命名为where。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM