Copying Files
This section describes how to use PHP to copy files.
The following example illustrates how to copy the contents of one file to another file:
filecopy.php
<?php
$orig_filename = "myfile.txt";
$new_filename = "myNewfile.txt";
$status = copy($orig_filename, $new_filename) or die("Could not copy file contents");
echo "Contents sucessfully copied";
?>
The first step is to create a variable to hold the full path to the original file whose contents will be copied:
$orig_filename = "myfile.txt";
Next, a second variable is created to hold the full path to the new file that will be created:
$new_filename = "myNewfile.txt";
The copy() function is executed, accepting two parameters, the path of the original file - $orig_filename, and the path of the new file - $new_filename. The copy() function returns a value of true if the copy is completed successfully;otherwise a value of false is returned. The returned value is stored in the variable $status.
$status = copy($orig_filename, $new_filename) or die("Could not copy file contents");
If the copy() function fails, the die() function executes displaying an error message. Otherwise, success message is displayed using the echo statement.
echo "Contents sucessfully copied";
In the previous section, the fwrite() function was used along with the fread() function to read the contents of one file and write the contents to a new file. Unless the contents of the original file are being appended to an existing file, the copy() function provides a more straightforward approach for copying content from an existing file to a new file.