How to Copy a File to a New Destination in PHP
In this article, you will learn how to copy an existing file to a new
destination in PHP using the native copy() function. We
will cover the basic syntax, walk through a practical code example, and
highlight important security and error-handling considerations to ensure
your file operations run smoothly.
The simplest way to copy a file in PHP is by using the built-in
copy() function. This function duplicates a file from a
source path to a specified destination path.
The Syntax of copy()
The copy() function requires two main arguments:
copy(string $source, string $dest, resource $context = ?): bool$source: The path to the source file you want to copy.$dest: The destination path where the file will be copied, including the new filename.$context(Optional): A custom context resource.
The function returns true on success or
false on failure.
PHP copy() Code Example
Here is a straightforward example demonstrating how to copy a file and handle potential errors:
<?php
$sourceFile = 'path/to/source/document.txt';
$destinationFile = 'path/to/destination/backup_document.txt';
// Check if the source file actually exists before copying
if (file_exists($sourceFile)) {
// Attempt to copy the file
if (copy($sourceFile, $destinationFile)) {
echo "File copied successfully!";
} else {
echo "Failed to copy the file.";
}
} else {
echo "Source file does not exist.";
}
?>Important Considerations
- Overwriting Files: If the destination file already
exists, the
copy()function will overwrite it without warning. If you want to prevent this, usefile_exists($destinationFile)to check the destination before callingcopy(). - Directory Permissions: PHP must have write
permissions for the destination directory and read permissions for the
source file. If permissions are incorrect, the function will fail and
emit an
E_WARNING. - Creating Directories: The
copy()function cannot create non-existent directories. You must ensure the destination folder already exists, or create it beforehand using themkdir()function.