Skip to content

Coping in File in PHP

In PHP, copying a file is straightforward thanks to the built-in copy() function. This function allows you to create a duplicate of an existing file and place it in a new location or rename it within the same directory.

Syntax of the copy() Function

php

Copy code

copy(source, destination)

  • source: The path to the file you want to copy.
  • destination: The path to where you want the copy to be created (can include a different name or directory).

How copy() Works

  1. PHP reads the contents of the source file.
  2. It writes the contents to the destination file.
  3. If the destination file exists, copy() will overwrite it without warning.
  4. The function returns TRUE on success and FALSE on failure.

Basic Example of Copying a File

Let’s say you have a file called “example.txt” in the current directory, and you want to copy it to a new file named “example_copy.txt”.

<?php

$source = “example.txt”;

$destination = “example_copy.txt”;

if (copy($source, $destination)) {

    echo “File copied successfully.”;

} else {

    echo “Failed to copy the file.”;

}

?>

In this example:

  • The copy() function attempts to duplicate “example.txt” and create “example_copy.txt”.
  • If the copy is successful, it outputs “File copied successfully.” Otherwise, it outputs an error message.

Copying a File to Another Directory

You can also copy a file to a different directory. Just specify the path in the destination parameter.

<?php

$source = “example.txt”;

$destination = “backup/example_copy.txt”; // ‘backup’ is a folder

if (copy($source, $destination)) {

    echo “File copied to the backup directory successfully.”;

} else {

    echo “Failed to copy the file.”;

}

?>

In this example, the file “example.txt” is copied to the “backup” directory with the new name “example_copy.txt”. Make sure the backup directory exists and has the necessary permissions.

Error Handling and File Permissions

Sometimes, copy() may fail due to:

  • The file not existing at the source path.
  • The destination path not being writable.
  • Insufficient permissions.

To handle these situations, use conditional checks before copying:

<?php

$source = “example.txt”;

$destination = “backup/example_copy.txt”;

// Check if the source file exists

if (!file_exists($source)) {

    die(“Error: Source file does not exist.”);

}

// Check if the destination is writable

if (!is_writable(dirname($destination))) {

    die(“Error: Destination directory is not writable.”);

}

// Attempt to copy the file

if (copy($source, $destination)) {

    echo “File copied successfully.”;

} else {

    echo “Failed to copy the file.”;

}

?>