Copy file from one directory to another directory in PHP

In this tutorial, I am going to show you a method of copy file from one directory to another directory in PHP.

Copy a file to another directory in PHP is going to be an easy task. Here I am going to tell you how you can do it with simple and easy code snippets with code snippets.

At first, take two directories. One is directory_1 and the other is directory_2.

In directory_1 we have a text file with the name Test.txt. Now we will copy it to another directory and change its name to Test_copy.txt.

Both of our directories are in the same parent directory.


PHP code to copy a file from one directory to another directory in PHP

Now below is our code to perform our task:

     // Our file to be copied
     $file = 'directory_1/Test.txt';
     // Destination location where we would like to move our file
     $dest_file = 'directory_2/Test_copy.txt';

         echo $file." failed to copy";
         echo $file. " copied into " .$dest_file;

The above code will be able to copy our file to another location.

In our code, we have used the PHP copy() function that done our main task. Below is the syntax of this function:


Using this function we can easily copy our file from one directory to another directory. This function exactly made for this particular task.

Here we have given our destination file a different name. Yes, you can also rename it during copying it and keep it with the different name.

You can notice that in the time of copying the file, we have first checked if our directory successfully copied or not. Depending upon the success and failure of the copy of our file, we are showing the message on our web page.

Now you can test the above code in your server and see what happen. If everything goes right, it will copy the Test.text file from directory_1 to and keep it in directory_2 with a new name Test_copy.txt.

So we have successfully able to copy our file from one folder to another in PHP easily. I hope you like our tutorial.

Leave a Reply

Your email address will not be published.