Copy a file from one directory to another in PHP
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.
|
1 2 3 4 5 6 |
<?php $src = '/path/to/directory/1.txt'; $dest = '/path/to/directory/2.txt'; copy($src, $dest); ?> |
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.
|
1 2 3 4 5 6 |
<?php $to = '/path/to/directory/1.txt'; $from = '/path/to/directory/2.txt'; rename($to, $from); ?> |
That’s all there is to copying a file from one directory to another in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)