Move a file from one directory to another in PHP

By Saruque Ahamed Mollick

In this tutorial, I will show you how easily you can move a file from one directory to another in PHP. Moving file from one folder to another, there is no such move() function in PHP. But in PHP we have rename() function which can be used to move a file in PHP.

Move a file in PHP with rename() method

To make you understand, assume that you have two directories or folders.

Copy file from one directory to another directory in PHP

Assume that the folders are: folder_1 and folder_2

In folder_1 you have a file with filename myfile.txt

Now you want to move this file to folder_2

The syntax of rename() function is:


How To Delete All Files In A Directory In PHP

Both of the two parameters are a string. So you can easily understand that you can use this function to rename a file easily in PHP

Go through this link to get to know.

How To Rename A File in PHP


The below code will now move a file from one directory to another.

$moved= rename('folder_1/myfile.txt', 'folder_2/myfile.txt');
  echo "Success";

Special Note:

If the file, which you want to be moved, does not exist then you will get a warning.

Hope this tutorial is helpful to you. Feel free to comment below. Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *