Copy file from one directory to another directory in PHP

In this tutorial, I am going to show you a method of copy a 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 a simple and easy example of code snippets.

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 program to copy a file from one directory to another directory in PHP

Now below is our code to perform our task:

<?php
     // 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';

     if(!copy($file,$dest_file))
     {
         echo $file." failed to copy";
     }
     else
     {
         echo $file. " copied into " .$dest_file;
     }
?>`

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

In our above program, we used the PHP copy() function that did our main task. Below is the syntax of this function:

copy(file,to_file)

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 a different name.

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

Now you can test the above code in your server and see what happens. 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 been 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. Required fields are marked *