How to Copy a File in PHP



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.

bool copy ( string $source , string $destination )
  • $source: The path to the source file.
  • $destination: The path to the destination file.
  $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.