PHP - Copy a file from one directory to another

By IncludeHelp Last updated : January 10, 2024

Problem statement

Write a PHP program to copy a file from one directory to another.

Copying a file from one directory to another

Use the copy() function by passing the source and target directory names. Keep the file name the same, if you don't want to change the file name in the target directory or use the different file name to copy with a new name in the target directory.

The syntax of the copy() function is:

copy(string $source_path, string $target_path, ?resource $context = null)

On the successful copy, the method returns true; false, otherwise.

PHP program to copy a file from one directory to another

<?php
try {
    // source path with the file name
    $source_path = "E:/Samples/file1.txt";

    // target path with the file name
    $destination_path = "E:/php_programs/file2.txt";

    // copying the file from source path to directory path
    if (!copy($source_path, $destination_path)) {
        echo "File copied.";
    } else {
        throw new Exception("Failed.");
    }
} catch (Exception $e) {
    echo "Error occurred: " . $e->getMessage();
}
?>

Output

Output of the above program is:

File copied.

Copying without changing the name of the file

If you do not want to change the file name in the targeted directory. Do not change the file's name in the target path.

See the variable initialization:

// source path with the file name
$source_path = "E:/Samples/file1.txt";

// target path with the file name
$destination_path = "E:/php_programs/file1.txt";

To understand the above program, you should have the basic knowledge of the following PHP topics:

More PHP File Handling Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.