Copy a file with PHP.

This is a short tutorial on how to copy a file using PHP.

To do this, we will be using PHP’s native copy function.

In this particular example, we will copy a zip file called to a directory called files.

Take a look at the following example.

//The location of the file that we want to copy.
$fileToCopy = '';

//The file path that we want to copy it to.
$destinationOfCopy = 'files/';

//Copy the file using PHP's copy function.
$success = copy($fileToCopy, $destinationOfCopy);

//Check if the copy was successful.
    //Print out a message.
    echo $fileToCopy . ' was copied to ' . $destinationOfCopy;

In the PHP code above, we copied to files/

If the file that you are attempting to copy does not exist, then your script will throw the following warning.

Warning: copy( failed to open stream: No such file or directory.

You will also receive a similar error if the destination folder does not exist.

This brings us to our next point.

This function will NOT create directories for you.

The copy function will not create directories for you, so you will have to make sure that the destination folder exists beforehand. Read more on how to do this.

The destination parameter must contain the name of the new file.

When using the copy function, you must always specify the filename in the destination parameter. In other words, you can’t just provide it with a folder name. It must also contain the name of the file.

If you omit the filename, then you will receive the following warning.

Warning: copy(): The second argument to copy() function cannot be a directory.

If the operation is successful, then the copy function will return a boolean TRUE value.

PHP’s copy function will overwrite files!

If the destination file already exists, then the copy function will overwrite it! As a result, you might want to check if the file already exists before you attempt to move it.

See also: Moving files with PHP.