Copy a file from one directory to another in PHP
In this article, we will explain to you how to copy a file from one directory to another in PHP. In the upcoming articles, we’ll also show you how to rename, move or delete a file using PHP.
Copy a file using PHP
Using the built-in function copy()
, we can copy a file in the same directory or one to another directory. It’s a very simple and easy way to copy a file using PHP.
This function requires two required arguments: the first one is the source path (A file path of file which wants to be copied) and second one is the destination path (A file path where copy a file). The copy()
function returns a true on success otherwise false as a boolean value.
Note: If the source file already exists in the destination folder then it will be overwritten.
Let’s check the syntax and simple examples.
Syntax
1 | bool copy( string $source, string $destination [, resource $context ] ) |
Parameters
- $source: It specifies the file path that you want to copy.
- $destination: It specifies the file path where you want to copy.
- $context: This is an optional parameter. It specifies the context resource created with the
stream_context_create()
function.
Example 1: Copy a file in the same directory
In the following example, we will see how to copy a file named file1.txt
to file2.txt
in the same directory.
1 2 3 4 5 6 7 8 9 10 | <?php $filepath = './file1.txt'; $newfilepath = './file2.txt'; if(copy($filepath, $newfilepath)){ echo "File has been copied"; } else { echo "Failed to copy file"; } ?> |
Example 2: Copy a file from one directory to another.
In this second example, we will copy a file from one directory to another directory. The code for both examples is the same, only the paths are different.
1 2 3 4 5 6 7 8 9 10 | <?php $filepath = '../directory1/file1.txt'; $newfilepath = '../directory2/file2.txt'; if(copy($filepath, $newfilepath)){ echo "File has been copied"; } else { echo "Failed to copy file"; } ?> |
That’s it for today.
Thank you for reading. Happy Coding..!!