PHP: Rename or move a file on the server
Working with server-side files with PHP adds a great deal of flexibility to some applications. A common scenario when working with files involves creating a temporary file through uploading or other means and then renaming this file to a permanent location. This recipe describes changing the name of an existing file using the PHP function rename().
The syntax for the PHP rename function is consistent with that of the UNIX mv function, which always makes things more comfortable. The general syntax is:
rename('/path1/old_filename', '/path2/new_filename');
The rename function returns true if the rename was successful, and false otherwise.
Just like with the unlink function which deletes files, the rename function most likely fails because of file permissions. To rename a file, the directory containing it must be writable by the user trying to rename it. The file’s permissions (and ownership) are irrelevant.










romanian devil said on March 29, 2009
very useful. it works
Tobias Hinz said on January 11, 2010
this is nice
Travel said on February 5, 2010
thanx
Anonymous said on February 17, 2010
but.. how to use $newname (post funtion)
Eddie Monge said on March 16, 2010
rename($oldname, $newname);
Anonymous said on May 10, 2010
Superb…..Thanks a lot.
Jjuntado said on June 14, 2010
great. it really helps. thanks
Calories in food said on November 8, 2010
Just like with the unlink function which deletes files, the rename function most likely fails because of file permissions.
javier said on November 23, 2010
Hi all!
I’m new in PHP, so I hope my question does not hears fool.
I need to change the name of a file in a webserver (Linux).
I wrote a file like this, upload it to the server, put it on the same folder as the rest, but nothing happens.
The permissions for the folder and files have all of them, execute rigths…
It seems that it needs something to make execute the order in this file…
I’m missing some aditional step?
Thanks for any help…
Javier
Muhire Kavuna said on September 20, 2011
Thanks a lot. It was very helpful.