Home > PHP > Moving Files In PHP

Moving Files In PHP

November 11th, 2008 Leave a comment Go to comments

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.

Information, services, and products:
are you thinking of Moving House
Categories: PHP Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.