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

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