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.

 

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.

  • romanian devil

    very useful. it works

  • this is nice

  • thanx

  • Anonymous

    but.. how to use $newname (post funtion)

  • Anonymous

    Superb…..Thanks a lot.

  • Jjuntado

    great. it really helps. thanks

  • Calories in food

    Just like with the unlink function which deletes files, the rename function most likely fails because of file permissions.

  • 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

  • Thanks a lot. It was very helpful.

  • David Smith

    Thanks qmchenry! +1’d for you 🙂

  • Mike Carter

    Hi Quinn — THIS is driving me nuts! I can NOT get any of the three methods of Copy, Rename, Move to work. The line of code is moronically simple. Thus, the nuts part.

    I tried changing permissions to 777 for the folder and recursive to the files within it. This is a test site so I’m not worried about 777 and security. I just want it to work.

    I used the absolute address to be certain the file was found.

    Have you any clue why it doesn’t rename (or Copy)?

    Thanks, Mike