How to Copy a File in PHP

09/07/2021

Contents

In this article, you will learn how to copy a file in PHP.

PHP copy() Function

In PHP, you can use the copy() function to copy a file from one location to another. The function returns TRUE on success, and FALSE on failure.

Syntax:
bool copy ( string $source , string $destination )
Parameters:
  • $source: The path to the source file.
  • $destination: The path to the destination file.
Example:
<?php
  $source = 'source_file.txt';
  $destination = 'destination_file.txt';

  if (copy($source, $destination)) {
    echo "File successfully copied.";
  } else {
    echo "File copy failed.";
  }
?>

In this example, $source is set to the path of the source file and $destination is set to the path of the destination file. The copy function is then called, passing in the source and destination file paths as arguments. If the copy operation is successful, the message “File successfully copied.” is displayed, and if it fails, the message “File copy failed.” is displayed.

Note: It is important to have the necessary file permissions to perform the copy operation. If the source file is not readable or the destination file is not writable, the copy function will fail.