Moving Files In PHP

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.

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

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:

rename("directory/directoryold","directory/directorynew");

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.
CAPTCHA
7 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.