Moving files with PHP

There are two main ways to move files in PHP - either copy the file to the new location, then delete the old one, or rename the file to the new location. There are a few different problems with both ways of doing it, and in this short guide I’ll try to cover as many different advantages and disadvantages of both ways.

Here’s a sample function on the copy/unlink method:

    function move_file( $oldfilelocation, $newfilelocation)
        {
        if( copy( $oldfilelocation, $newfilelocation ) )
            {
            unlink( $oldfilelocation );
            }
        else
            {
            echo "Copy failed";
            }
        }

The function’s rather simple - it’s broken up into an if-else pair - if the file copies from the old location to the new location, then unlink (delete) the old file. If the copy fails, echo a generic error message. You could put all sorts of things into this “error” section, things like logging the error to a database, or echo’ing something to the screen.

Pros:

It’s simple, and easy to debug if something goes wrong - and since it’s only copying the file, then checking that it’s there, then deleting the original, the file isn’t going to go missing like if you had just moved it to the wrong spot.

Cons:

Adds another function or another if-else statement to your codebase, adding more complexity in your script, and something else to debug.

The rename() function is quite powerful:

rename( $oldfilename, $newfilename );

That’s all you need to do when you’re renaming a file (or moving it to a new location.) As an example, if I was moving “tempfile.txt” from /var/www/html to /var/www/html/backup all I would have to do is call the function as follows:

rename( "/var/www/html/tempfile.txt", "/var/www/html/backup/tempfile.txt" );

The problem with this is that there is no checking whether the original file is there, there is no check done on if the file was able to be moved or any error reporting - it’ll report whether it worked or not, but there’s no sure-fire way of knowing that it did, unless you were using the rename function inside some if-else code.



#Programming