Move a file with PHP.

In this tutorial, we will show you how to move a file using PHP.

To do this, we will be using PHP’s native rename function. As the name suggests, this function renames a given file or directory.

Don’t let the name of the function confuse you. By renaming the path to the file, we are essentially moving it.

For this tutorial, we will create two directories called directory_a and directory_b.

In directory_a, we have a text file called sample-file.txt.

Using PHP, we are going to move sample-file.txt from directory_a to directory_b.

Take a look at the following example.

//The file path of the file that we want to move.
//In this case, we have a txt file called sample-file.txt
$currentFilePath = 'directory_a/sample-file.txt';

//Where we want to move the file to. In this example, we
//are moving the .txt file from directory_a to directory_b
$newFilePath = 'directory_b/sample-file.txt';

//Move the file using PHP's rename function.
$fileMoved = rename($currentFilePath, $newFilePath);

    echo 'Success!';

In the code above.

  1. We specified the file path of the current file. This is the file that we want to move.
  2. After that, we specified the new file path. This is the path and filename that we want our new file to have. In other words, this is where we want to move it to. Note that if you want to give it a different filename, then you can simply change the “sample-file” segment of the $newFilePath variable to something else.
  3. In order to move the file, we used PHP’s rename function. PHP’s rename function takes in $currentFilePath as the first parameter ($oldname) and $newFilePath as the second parameter ($newname).
  4. If the move is successful, then the rename will return a boolean TRUE value.

The rename function will overwrite existing files!

It is important to note that the rename function will overwrite existing files. In other words, if $newFilePath is the name of an existing file, then that file will be overwritten.

As a result, you might need to be careful about blindly moving files.

The file that you want to move must exist.

If $currentFilePath does not exist, then the following PHP warning will be thrown.

“Warning: The system cannot find the file specified.”

To guard against these kind of issues, you can use PHP’s is_file function to see if the files exist or not before you attempt to move it.

A code sample showing what this might look like.

    $fileMoved = rename($currentFilePath, $newFilePath);
        echo 'Success!'; 

In the PHP above, we checked to see if the file already exists before we called the rename function. This way, we can be sure that we’re not overwriting something by mistake.

See also: Copying files with PHP.