Move file and rename it

Setting up PHP renaming could be best. I have not seen many examples of how to use relative URLs in it, so I'm kind of compromised. Anyway, this gives me permission:

I want to do this:

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

Where ../ , of course, will return 1 directory from which the script is executed. I could not 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 get permission (yes, the history folder belongs to www-data, and data.csv belongs to www-data). I thought it was weird, so I tried a simple test:

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

and I made sure www-data has full control over tempfile.txt ... still got permission. What for? should the file you rename exist? can you rename like linux mv? So instead I just copy () and unlink ()?

+4
source share
2 answers

To move a file from "../" to "../history/", the process must have write permissions for both "../" and "../history/".

In your example, you obviously lack write permissions on "../". Permissions for the moved file, by the way, are irrelevant.

+4
source

Not only the role plays a role, but also the file permissions. Make sure that the permissions are correctly configured in the source file and destination directory (for example, chmod 644 data.csv ).

Is www-data the same user as apache?

Edit: Take care of providing existing, absolute paths to realpath() . Also beware of the following:

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

This will not do anything because the ../data.csv file may not exist. Ie The result of realpath() in a nonexistent file is false .

Here is the code that might work best for you:

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

You should be extremely careful that the visitor does not edit $file , because he could modify the request by manipulating which file was renamed to.

+1
source

All Articles