copy a file in PHP.


Answers ( 1 )

    // Copying a file in PHP
    $sourceFile = 'source.txt';
    $destinationFile = 'destination.txt';
    // Using the copy() function to copy the file
    if (copy($sourceFile, $destinationFile)) {
        echo "File copied successfully.";
    } else {
        echo "File copy failed.";

    In this example, source.txt is the file that you want to copy, and destination.txt is the name of the new file that you are creating as a copy of the source file. The copy() function returns true if the file was copied successfully and false if it failed.

    There are several things to consider when using the copy() function:

    1. File Permissions: The PHP process must have the necessary permissions to read the source file and write the destination file.

    2. File Paths: You can use both relative and absolute paths for the source and destination files. If you're using relative paths, they are relative to the current working directory of the script.

    3. Overwriting Files: If the destination file already exists, it will be overwritten without any warning.

    4. Error Handling: It's important to handle errors properly. The copy() function will return false on failure, which can be used to implement error handling, as shown in the example.

    5. Large Files: Be cautious when copying large files, as it might impact the performance of your script and the server.

    6. Binary Files: The copy() function works well with both text and binary files (like images, PDFs, etc.).

    This is a straightforward way to copy files in PHP. There are other, more complex methods for copying files (like using file streams), but for most use cases, the copy() function should suffice.

Leave an answer