PHP: Rename or move a file on the server

Posted July 10, 2006 by Quinn McHenry in PHP programming

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.

 

About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.