Copying files in PHP

Tutorial on how to copy files with PHP. Copying files can be done with the file fopy function.

Copying files can be done with the copy function of PHP, this function will also accept URLs in the source parameter, given that the fopen wrappers has been enabled.

Copying files is really simple, the below example shows how to copy a text file, renaming it in the process. Keep in mind that the destination file will be overwritten if it already exists, so it can be a good idea to rename the file if you don't want that to happen.

<?php
$file = 'MyTextFile.txt';
$newfile = 'MyTextFile-copy.txt';

if (!copy($file, $newfile)) {
    echo "failed to copy $file.";
}
?>

The above consists of two variables and a single if statement, the if statement will check if the file copy failed. The copying is happening inside the if-check, so do not be confused about this. It simply runs the function, and then checks the return value.

Copying Files to Directories

When copying a file to another directory, you should first create the directory before it will be possible to copy files to it. If the directory already exists, just do something like:

<?php
$source = 'MyTextFile.txt';
$destination = 'mydir/MyTextFile-copy.txt';

if (!copy($source, $destination)) {
    echo "failed to copy: <strong>$source</strong>";
}
?>

Copying remote files

Remote files are located on other servers, copying them will mean that you have to download them. The copy function can also be used on remote files, given that the fopen wrappers are enabled.

The below example demonstrates how to use copy to download remote files. Note. You won't be able to download the source-code of remote PHP scripts!

<?php
  if(!copy('http://example.com/myfile.txt','mydir/FileName.txt')) {
    $errors = error_get_last();
    echo '<strong>Error Type:</strong> '.$errors['type'] . '<br>';
    echo '<strong>Error Message:</strong> ' . $errors['message'];
  }
?>

See also

  1. Create and Write to Files
  2. Read Content of Files
  3. Deleting Files and Directories
  4. Renaming Files