PHP 101
  • Home
  • Deploy
  • How-to
  • Tutorial
No Result
View All Result
PHP 101
  • Home
  • Deploy
  • How-to
  • Tutorial
No Result
View All Result
PHP 101
No Result
View All Result
Home How-to

How to copy files using PHP

Easy and in-depth guide on how to copy files and directories using PHP.

August 29, 2022
Reading Time: 4 mins read
PHP101.Net - How to copy files using PHP

PHP101.Net - How to copy files using PHP

Share on FacebookShare on Twitter

This short guide will help you on how to copy files using PHP.

Quick solution

We can use PHP’s copy() function to quickly copy the files from source to destination path.

Assuming we have a source_file.txt and wanted to copy the file and rename it to dest_file.txt:

copy('/source/source_file.txt', '/dest/dest_file.txt');

The source_file.txt file will be copied and renamed as dest_file.txt.

On some occasions, copy() command will fail on Windows operating system, or being disabled on some hostings due to security purpose. We can use other methods to copy files using PHP which will be described below.

How to copy files using PHP

There will be three methods to copy files using PHP mentioned in this guide, the popular copy() function, using fwrite(), and executing command by shell_exec() function.

Copy files in PHP using copy() function

This is the most popular method to copy files using PHP. The function will return a boolean value indicating whether the copy process is successful or not:

// $copyResult will return true or false
$copyResult = copy('/source/source_file.txt', '/dest/dest_file.txt');

Make sure destination folder exists

Make sure the destination folder exists first, or the copy command will fail. We can create the destination  folder recursively first using mkdir() function to avoid non-existent destination path:

// Destination folder and file
$destFolder = '/dest/folder/';
$destFile = $destFolder . 'dest_file.txt';

// Create the destination folder first. Chmod permission can be adjusted depends on your case.
mkdir(dirname($destFolder), 0777, true);

// Do the copy 
$copyResult = copy('/source/source_file.txt', $destFile);

Copy files in PHP using fwrite() function

Several web hosting disables copy() function for security purposes. In Windows operating system, the copy() function sometimes fail to process large files. That’s when PHP’s File stream functionality comes in handy.

Below is the full script for copying files using PHP File stream functionality. This includes a number of functions as fopen(), fwrite(), fclose() for handling file stream and file_get_contents() to read file content.

// Define source and destination file
$sourceFile = '/source/source_file.txt';
$destFile = '/dest/dest_file.txt';

// Get file content for opening using stream
// ** Note: if file_get_contents() is disabled, see below note
$fileContent = @file_get_contents($sourceFile);

// Set destination file to stream handler with write mode
$destFileStream = fopen($destFile, 'w');

// Write source file content to destination file path
fwrite($destFileStream, $fileContent);

// Close the stream after writing
fclose($destFileStream);

Note: Many web hosting have file_get_contents() disabled due to security reasons. In that case, we can use fopen() and stream_get_contents() functions to get the file content:

// Open source file in read mode for reading
$sourceFileStream = fopen($sourceFile, 'r');

// Get file content from stream and close the stream
$fileContent = stream_get_contents($sourceFileStream);
fclose($sourceFileStream);

Copy files in PHP using shell_exec() function

Another unpopular method for copying files and directories using PHP is make use of shell command. Using this method will have PHP executing the command in shell to copy the files and directories.

For example, in Linux shell, this command will be used for copying the files and directories recursively:

cp -r -a /source_dir/* /dest_dir/*

…which will copy all files and directories from /source_dir/ to /dest_dir/ recursively.

We can use PHP to do the same copy job using shell command:

$copyJob = shell_exec("cp -r -a /source_dir/* /dest_dir/*");

Important note: While this method would work, it poses potential security risks having shell_exec() function enabled. In fact, most of web hosting have this function disabled and cannot be used with PHP.

Copy remote URL/file

The copy() function can also copy remote files as an URL:

copy('http://example.com/file.txt', './file.txt');

Recursive copy files and directories

The below script will copy the files and directories recursively, creating the destination directories where needed.

function recursive_copy($source, $dest) {

    // Open source directory using directory handler
    $sourceDir = opendir($source);

    // Create directory on destination, ignore error messages
    @mkdir($dest);

    // Loop through the source directory files using readdir()
    while(( $file = readdir($sourceDir)) ) {

        // Proceed if $file is actually a file (not current/previous directory)
        if (( $file != '.' ) && ( $file != '..' )) {

            // Attach $source and $file to see whether it's a directory 
            if ( is_dir($source . '/' . $file) ) {
                
                // It's a directory: Loop through the function again
                recursive_copy($source .'/'. $file, $dest .'/'. $file);
            }
            else {
                // It's a file: Proceed to copy the file
                copy($source .'/'. $file, $dest .'/'. $file);
            }
        }
    }
    // Close directory handle
    closedir($dir);
}

Final thought

Copying files from PHP can be very easy or complicated, depends on the approach and how you want the copying process to work. This article mentioned the most popular methods to copy files using PHP.

You might also like

  • How to convert from array to string in PHP
  • How to download file from URL using PHP

References

  • PHP.net Official Documentation – copy() function
  • PHP.net Official Documentation – fopen() function
  • PHP.net Official Documentation – fwrite() function
  • PHP.net Official Documentation – fclose() function
Tags: php copy filephp copy filesphp copy files and directoriesphp copy()
Previous Post

How to count array elements in PHP

Next Post

How to convert image to base64 using PHP

Related Posts

PHP101.net - How to set timezone with PHP

How to set timezone with PHP easily (multiple methods)

March 9, 2023
PHP101.net - How to redirect to another page using PHP

How to redirect to another page using PHP

March 8, 2023

Table of Contents

    • Quick solution
    • How to copy files using PHP
    • Copy files in PHP using copy() function
    • Make sure destination folder exists
    • Copy files in PHP using fwrite() function
    • Copy files in PHP using shell_exec() function
    • Copy remote URL/file
    • Recursive copy files and directories
    • Final thought
    • You might also like
    • References
Next Post
PHP101.Net - How to convert image to base64 using PHP

How to convert image to base64 using PHP

We deliver free and helpful resources for learning
and using PHP programming language.

About
Contact Us
Privacy Policy
Main Sections

Home
Deploy
How-to
Tutorial
You might be interested in...

How to redirect to another page using PHP

How to install Composer on Linux

How to install PHP GeoIP extension & GeoLite2 library (databases included)

Deploy a webserver with XAMPP on Windows for PHP development

How to set timezone with PHP easily (multiple methods)

© 2022 PHP101.Net - Helpful PHP Tutorials, How-to, Tips and Tricks for everyone.

No Result
View All Result
  • Home
  • Deploy
  • How-to
  • Tutorial

© 2022 PHP101.Net - Helpful PHP Tutorials, How-to, Tips and Tricks for everyone. | Privacy Policy

This website uses cookies. By continuing to use this website you are giving consent to cookies being used. Visit our Privacy and Cookie Policy.