How to Copy a File Using PHP

PHP



In this article, we show how to copy a file using PHP.

Copying files may be necessary for many reasons.

Copying a file means that you take a complete file and make a copy of it. The new file is then called a different name. All the contents that are in the original file are copied to the copy of the original file.

The names of the files must be different, however, the only thing that is different, because files cannot have the same exact name.

So how is this done with PHP?

PHP has a copy() function that allows us to make a copy a file.

So the PHP code to make a copy of a file is shown below.




So the code above is very simple. It's a single line.

The PHP copy() function takes in 2 parameters.

The first parameter is the original file that we want to copy. In this parameter, we must specify the file name along with its file extension. Do not leave off the file extension, or else the function will not work.

The second parameter represents the new copied file. Again, we must specify the file name along with its file extension. In the second parameter, you specify what you want the new copied file to be named. This new file contains all the contents in it that the original file has; the only difference is the file name is different. 

So this is all that is needed to copy a file.

Even though the code is above is very effective and does the job of copying a file, many times we would want to add more to it, so that we can get more information. For example, does the file we want to copy exist? If the file does exist, was it successfully copied?

The PHP code below copies a file and gives us more information.



This code now is more forthwise. It tells us more.

We first see whether the file exists. If the file exists, the code advances to the next line. In this line, we create a variable named $copied. This variable holds the result of the PHP copy function. If the file has been copied successfully, the $copied variable will hold a 1 or TRUE value. If it hasn't, the $copied variable will hold a 0 or FALSE value. If the file has been copied successfully, the line "The file has been successfully copied" is output. If not, the line "The file has not been successfully copied" is output.

If the file doesn't exist, the line "The original file that you want to copy doesn't exist" is output.

So this code above tells us everything. It tells us whether the file we want to copy exists. And it tells us whether the file copy was successful or not.

And this is all that is required to copy a file using PHP. s



HTML Comment Box is loading comments...