Copying Files

This section describes how to use PHP to copy files on Windows systems.

PHP includes the copy() function for copying files. The function is defined below:

copy(original filename, new filename) - copies the contents of an original file defined by the first parameter to a new file defined by the second function parameter. The function returns a true or false value.

The following example illustrates how to copy the contents of one file to another file:

filecopy.php

<?php

$orig_filename = "C:/Documents and Settings/Administrator/MyFiles/myfile.txt";

$new_filename = "C:/Documents and Settings/Administrator/MyFiles/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 = "C:/Documents and Settings/Administrators/MyFiles/myfile.txt";

Next, a second variable is created to hold the full path to the new file that will be created:

$new_filename = "C:/Documents and Settings/Administrators/MyFiles/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.