Copy file from one directory to other in Php

To copy a file from one directory to another using PHP, we can utilize the `copy()` function.

bool copy ( string $srcLocation , string $dest [, resource $context ] )

The first parameter of the `copy()` function is the source location of the file, while the second parameter is the destination location.

Note: The third parameter, `$context`, is optional. If provided, it must be a valid context resource created with the `stream_context_create()` function.

Let's look at a basic example of copying a file,

<?php

$srcFileName = 'fileA.php';
$copyFileName = 'fileACopy.php';

if (!copy($srcFileName, $copyFileName)) {
    echo "Error occurred while copying file";
} else {
    echo "File copied successfully!";
}

?>

Here’s another example that demonstrates copying a file to a different directory,

<?php

$srcFileName = 'fileB.php';
$destDirectory = 'backup/';
$copyFileName = $destDirectory . 'fileBCopy.php';

if (!copy($srcFileName, $copyFileName)) {
    echo "Error occurred while copying file to backup directory";
} else {
    echo "File copied to backup directory successfully!";
}

?>

Note: If the destination file already exists, its contents will be overwritten.



Frequently Asked Questions (FAQ):

1. What happens if the source file does not exist?

- The `copy()` function will return false, and you will receive an error message.

2. Can I copy files across different servers?

- Yes, but you need to ensure that the destination server is accessible and that you have the necessary permissions.

3. How can I handle errors when copying files?

- You can check the return value of the `copy()` function and use error-handling techniques to manage any issues.

4. What should I do if I encounter a "Permission denied" error?

- Ensure that you provide the complete path with the file name for both the source and destination folders. If you only provide the path for the destination folder, you will encounter this error.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!