0
0
PhpHow-ToBeginner · 3 min read

How to Copy a File in PHP: Simple Syntax and Example

In PHP, you can copy a file using the copy() function by providing the source file path and the destination file path as arguments. This function returns true if the file is copied successfully, otherwise false.
📐

Syntax

The copy() function in PHP requires two parameters: the source file path and the destination file path. It returns true on success and false on failure.

  • source: The path to the file you want to copy.
  • destination: The path where you want the copy to be saved.
php
bool copy ( string $source , string $destination )
💻

Example

This example copies a file named example.txt to a new file named example_copy.txt in the same directory. It checks if the copy was successful and prints a message.

php
<?php
$source = 'example.txt';
$destination = 'example_copy.txt';

if (copy($source, $destination)) {
    echo "File copied successfully.";
} else {
    echo "Failed to copy file.";
}
?>
Output
File copied successfully.
⚠️

Common Pitfalls

Common mistakes when copying files in PHP include:

  • Using incorrect file paths for source or destination.
  • Not having proper permissions to read the source or write to the destination.
  • Trying to copy a file that does not exist.
  • Overwriting important files without checking.

Always check the return value of copy() to handle errors gracefully.

php
<?php
// Wrong: source file does not exist
if (!copy('nonexistent.txt', 'copy.txt')) {
    echo "Error: Source file missing.";
}

// Right: check if source exists before copying
$source = 'example.txt';
$destination = 'example_copy.txt';
if (file_exists($source)) {
    if (copy($source, $destination)) {
        echo "Copy succeeded.";
    } else {
        echo "Copy failed.";
    }
} else {
    echo "Source file does not exist.";
}
?>
Output
Source file does not exist.
📊

Quick Reference

FunctionDescriptionReturn Value
copy(source, destination)Copies a file from source to destinationtrue on success, false on failure
file_exists(path)Checks if a file exists at the given pathtrue if exists, false otherwise
is_readable(path)Checks if the file can be readtrue if readable, false otherwise
is_writable(path)Checks if the destination is writabletrue if writable, false otherwise

Key Takeaways

Use the copy() function with source and destination paths to copy files in PHP.
Always check if the source file exists and if copy() returns true to avoid errors.
Ensure you have proper permissions to read the source and write to the destination.
Avoid overwriting important files by verifying the destination path before copying.
Use helper functions like file_exists() to improve reliability.