This article demonstrates how to copy a file from one directory to another in PHP.

1. Using copy() function

The standard solution to copying a file from one directory to another is to use the copy() function. It returns true on success and false on failure. For example, the following solution uses the copy() function to make a copy of the file pointed by $src to $dest.

Download Code

 
It should be noted that if the destination file already exists, it will be overwritten. However, copy() does not create any new directories. Therefore, you should ensure that copying is done only to the existing paths. Also note that the destination should contain the full path along with the file name, and not just the path of the directory to copy into.

2. Using rename() function

If you need to move a file, consider using the rename() function. It returns true on success and false on failure. This removes the files from the source location, and the destination file will be overwritten if it already exists.

The following solution shows the usage of the rename() function to rename the file $to to $from and move it to a new path if necessary.

Download Code

That’s all there is to copying a file from one directory to another in PHP.