Moving Files In PHP

11th November 2008 - 2 minutes read time

I have been asked a couple of times recently if PHP has a function that will move a file, so I thought I would put the solution here.

PHP has a function called rename() which can be used to rename a file, but because of the way it works it can be used to move files. Let's say that you wanted to rename a file called test.txt to test_back.txt, this can be accomplished by doing the following.

rename("test.txt", "test_back.txt");

However, if you want to move the file from one directory to another you can do the following.

rename("test.txt", "backups/test_back.txt");

The return value of rename() is boolean that tells you if the rename was successful or not, this can be used to error check like this.

  1. if ( !rename("test.txt", "backups/test_back.txt") ) {
  2. // rename not successful, try another way
  3. }

Be aware that if you try the following:

rename("test.txt", "test.txt");

The function will return true.

To rename a directory you should do the following:


Note the absence of the trailing slash on the directory name, PHP will give an error if this slash is added.

Add new comment

The content of this field is kept private and will not be shown publicly.