Copying files in PHP is a common task, whether for backups, file manipulation, or uploading files.
PHP provides built-in functions to copy, move, rename, and check file existence before performing operations.
This tutorial will cover:
1. Copying Files Using copy()
The simplest way to copy a file in PHP is by using the copy() function.
Syntax:
copy(string $source, string $destination): bool
- $source: Path of the file to be copied.
- $destination: Path where the file should be copied.
- Returns true on success, false on failure.
Example: Copying a Single File
<?php $source = "source.txt"; $destination = "copy_source.txt"; if (copy($source, $destination)) { echo "File copied successfully!"; } else { echo "File copying failed!"; } ?>
- This script copies source.txt to copy_source.txt in the same directory.
2. Checking if a File Exists Before Copying
Copying a file that does not exist will result in an error. We can prevent this by using file_exists().
Example:
<?php $source = "source.txt"; $destination = "backup_source.txt"; if (file_exists($source)) { if (copy($source, $destination)) { echo "File copied successfully!"; } else { echo "File copying failed!"; } } else { echo "Source file does not exist!"; } ?>
- The script checks if the file exists before copying.
3. Handling Errors While Copying Files
The copy() function returns false on failure. We can use error_get_last() to get the error details.
Example: Handling Copy Errors
<?php $source = "non_existing_file.txt"; $destination = "backup.txt"; if (!copy($source, $destination)) { $error = error_get_last(); echo "File copying failed! Error: " . $error['message']; } else { echo "File copied successfully!"; } ?>
- If copying fails, it displays the error message.
4. Copying Multiple Files
To copy multiple files, use a loop.
Example: Copying Multiple Files
<?php $files = ["file1.txt", "file2.txt", "file3.txt"]; $destinationFolder = "backup/"; foreach ($files as $file) { $destination = $destinationFolder . $file; if (file_exists($file)) { if (copy($file, $destination)) { echo "Copied $file to $destination <br>"; } else { echo "Failed to copy $file <br>"; } } else { echo "$file does not exist! <br>"; } } ?>
- This script copies multiple files into the backup/ folder.
5. Copying Files with Unique Names
If the destination file already exists, we can create a unique copy by appending a timestamp.
Example: Copying with Unique Filenames
<?php $source = "document.txt"; $destination = "backup/document_" . time() . ".txt"; if (copy($source, $destination)) { echo "File copied as $destination"; } else { echo "File copying failed!"; } ?>
- The destination file name will be something like document_1710265631.txt.
6. Moving and Renaming Files
Instead of copying, you can move or rename files using rename().
Example: Moving a File
<?php $source = "old_folder/sample.txt"; $destination = "new_folder/sample.txt"; if (rename($source, $destination)) { echo "File moved successfully!"; } else { echo "File moving failed!"; } ?>
- This moves sample.txt from old_folder to new_folder.
7. Copying Uploaded Files
When a file is uploaded via a form, it is temporarily stored in the tmp directory. We use move_uploaded_file() to move it to a permanent location.
Example: Handling File Uploads
<?php if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) { $tempFile = $_FILES["file"]["tmp_name"]; $destination = "uploads/" . $_FILES["file"]["name"]; if (move_uploaded_file($tempFile, $destination)) { echo "File uploaded and copied successfully!"; } else { echo "File upload failed!"; } } ?> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form>
- This script uploads a file and saves it permanently in the uploads/ folder.
8. Manually Copying Files Using fopen()
PHP provides low-level file handling using fopen(), fread(), and fwrite().
Example: Copying a File Manually
<?php $source = "source.txt"; $destination = "manual_copy.txt"; $srcHandle = fopen($source, "r"); $destHandle = fopen($destination, "w"); while (!feof($srcHandle)) { $buffer = fread($srcHandle, 1024); fwrite($destHandle, $buffer); } fclose($srcHandle); fclose($destHandle); echo "File copied manually!"; ?>
- This reads the source file in chunks and writes it to the destination.
9. Checking File Permissions Before Copying
If the copy() function fails, it might be due to file permissions. We can check this using is_readable() and is_writable().
Example: Checking Permissions
<?php $source = "protected_file.txt"; $destination = "backup.txt"; if (is_readable($source) && is_writable(dirname($destination))) { if (copy($source, $destination)) { echo "File copied successfully!"; } else { echo "File copying failed!"; } } else { echo "Permission issue: Cannot read or write!"; } ?>
- Checks if the file is readable and the destination is writable.
Conclusion
- PHP provides copy() for simple file copying.
- Use file_exists() to check if the file exists before copying.
- Handle errors with error_get_last().
- Copy multiple files using a loop.
- Use timestamps to avoid filename conflicts.
- Move files using rename().
- Handle file uploads using move_uploaded_file().
- Manually copy files using fopen() for better control.