Copy a file with PHP.

This is a short tutorial on how to copy files using PHP. To do this, we will be using PHP’s inbuilt copy function.

In this particular example, I will copy a zip file called myfile.zip to a directory called files. Let’s take a look at the following example:

In the PHP code above, we copied myfile.zip to files/myfile-copy.zip. If the file that you are attempting to copy does not exist, then you will be met with the following error:

Warning: copy(incorrect-filename.zip): failed to open stream: No such file or directory.

You will also receive a similar error if the destination folder does not exist. The copy function will not create directories for you, so you will have to make sure that the destination folder exists beforehand.

When using the copy function, you must always specify the filename in the destination parameter. If you omit the filename, you will receive the following warning:

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

Note: If the destination file already exists, then the copy function will overwrite it!

See also: Moving files with PHP.

Facebook Comments