Move a file with PHP.

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:

In the code above:

  1. We specified the file path of the current file. i.e. The file that we want to move / rename.
  2. 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.
  3. 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.

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.

Comments

comments