How to copy a file in PHP using PHP’s copy () function


In this tutorial, you are going to learn how to copy a file in PHP using PHP’s copy () function.

The copy() function is a built-in function of PHP which is used to copy a file. Here, file means any kind of file like text, photos, etc. It copies the existing file to another new file.

Let’s understand the function step by step with examples. Suppose, we have a text file called “Original.txt”. Now we want to copy the file content to another file.

Copy a text file:

PHP copy file

The copy() function:

copy("Original.txt", "Copy.txt")

So, this is how the copy function works. It takes two parameters. The first parameter takes the file name we want to copy and the second one is the name of the upcoming new file.

<?php
     if(copy("Original.txt", "Copy.txt"))
     {
	 echo "Text file copied successfully";
     } else{
	 echo "Text file copied failed";
     }
?>

We can add an if-else condition just to check in the browser. But it is not necessary if you need only the copy() function.

OUTPUT:

PHP copy file

As you can see, we gave the name “Copy.txt” as a second parameter, and here is the output. If we open the two files simultaneously, the content of them will also be the same.

Copy a file to another folder:

Now if we want to copy a file to another folder, we can also do it with the copy() function.

PHP copy file

Here, we’re going to make a copy of “Original.txt” and paste it into the Newfolder as “Copy.txt”.

<?php

$originaFile = '/xampp/htdocs/PHPcodeExamples/Original.txt';
$newFile = '/xampp/htdocs/PHPcodeExamples/Newfolder/Copy.txt';

if (copy($originaFile, $newFile)) { 

    echo "Text file copied successfully"; 
} 
else { 
 
    echo "Text file copied failed"; 
} 
?>

In this example, inside of the copy() function, we have to give the path of the “Original.txt”. Because we are moving the file to another folder or directory. We need to take two variables, $originaFile, and $newFile. You can name your variables as you wish. In the first variable, we have to give the directory of “Original.txt” and the second variable takes the directory of the new folder. Then, we have to pass the variable names into the copy() function.

OUTPUT:

PHP copy file

Copy an image:

We can also copy an image in the same way. Let’s look at the example-

<?php

     if (copy("image.jpg", "copyimage.jpg")) { 

	 echo "Text file copied successfully"; 
     } 
     else { 
	 echo "Text file copied failed"; 
     } 
?>

OUTPUT:

PHP copy file

The copy() function actually returns TRUE on success and FALSE on failure. So, this is how you can use the PHP copy() function.


Share on social media

//