This is a tutorial on how to move files using PHP. To do this, we will be using PHP’s rename function, which essentially renames a given file or directory.
For this tutorial, I have created two directories called directory_a and directory_b. In directory_a, I have a text file called sample-file.txt In the code below, I will 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);
In the code above:
- We specified the file path of the current file. i.e. The file that we want to move / rename.
- We specified the new file path. This is the path and filename that we want our new file to have. i.e. 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 anything that you want to.
- 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).
- If the move is successful, then the rename will return a boolean TRUE value.
NOTE! If $newFilePath is the name of a currently-existing file, then that file will be overwritten by the rename function.
NOTE! If $currentFilePath does not exist, then a PHP warning will be thrown:
Warning: The system cannot find the file specified.
To guard against the issues that were listed above, you can use PHP’s is_file function to see if the files exist or not.
See also: Copying files with PHP.