Transfer Files Server to Server Using Simple PHP

server-to-server-php-zip

Sometimes you need to move/migrate files to another server/hosting, and you/your client only have FTP access to the server. And to download these files and re-upload to another server can take a lot of time using FTP client such as Filezilla. FTP do not have zip – unzip functionality, so you need to upload it one by one. And server to server transfer is a lot faster than downloading and uploading the files.

You can use this simple PHP script to move files from one server to another server.

Note: It’s just a simple examples. you need to build your own auth/security method if needed.

1. Using PHP Copy to move files from server to server.

You can just create a php file in the destination server and load the file once in your browser. For example you add this code in http://destination-url/copy-files.php and in copy-files.php you add this php code:

/**
 * Transfer Files Server to Server using PHP Copy
 * @link https://shellcreeper.com/?p=1249
 */

/* Source File URL */
$remote_file_url = 'http://origin-server-url/files.zip';

/* New file name and path for this file */
$local_file = 'files.zip';

/* Copy the file from source url to server */
$copy = copy( $remote_file_url, $local_file );

/* Add notice for success/failure */
if( !$copy ) {
    echo "Doh! failed to copy $file...\n";
}
else{
    echo "WOOT! success to copy $file...\n";
}

2. Using PHP FTP to move files from server to server

Sometimes using PHP Copy didn’t work if the files is somehow protected by this method (hotlink protection maybe?). I did experience that if the source is from Hostgator it didn’t work.

But we can use another method. Using FTP (in PHP) to do the transfer using the code:

/**
 * Transfer (Import) Files Server to Server using PHP FTP
 * @link https://shellcreeper.com/?p=1249
 */

/* Source File Name and Path */
$remote_file = 'files.zip';

/* FTP Account */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = '[email protected]'; /* username */
$ftp_user_pass = 'ftppassword'; /* password */


/* New file name and path for this file */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Download $remote_file and save to $local_file */
if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
    echo "WOOT! Successfully written to $local_file\n";
}
else {
    echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );

using FTP you have more flexibility, the code above is using ftp_get to import the files from source server to destination server. But we can also use ftp_put to export the files (send the files) from source server to destination, using this code:

/**
 * Transfer (Export) Files Server to Server using PHP FTP
 * @link https://shellcreeper.com/?p=1249
 */

/* Remote File Name and Path */
$remote_file = 'files.zip';

/* FTP Account (Remote Server) */
$ftp_host = 'your-ftp-host.com'; /* host */
$ftp_user_name = '[email protected]'; /* username */
$ftp_user_pass = 'ftppassword'; /* password */


/* File and path to send to remote FTP server */
$local_file = 'files.zip';

/* Connect using basic FTP */
$connect_it = ftp_connect( $ftp_host );

/* Login to FTP */
$login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );

/* Send $local_file to FTP */
if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
    echo "WOOT! Successfully transfer $local_file\n";
}
else {
    echo "Doh! There was a problem\n";
}

/* Close the connection */
ftp_close( $connect_it );

To make it easier to understand:

  • ftp_connect is to connect via FTP.
  • ftp_login is to login to FTP account after connection established.
  • ftp_close is to close the connection after transfer done (log out).
  • ftp_get is to import/download/pull file via FTP.
  • ftp_put is to export/send/push file via FTP.

After you import/export the file, always delete the PHP file you use to do this task to prevent other people using it.

ZIP and UNZIP Files using PHP

Of course to make the transfer easier we need to zip the files before moving, and unzip it after we move to destination.

ZIP Files using PHP

You can zip all files in the folder using this code:

/**
 * ZIP All content of current folder
 * @link https://shellcreeper.com/?p=1249
 */

/* ZIP File name and path */
$zip_file = 'files.zip';

/* Exclude Files */
$exclude_files = array();
$exclude_files[] = realpath( $zip_file );
$exclude_files[] = realpath( 'zip.php' );

/* Path of current folder, need empty or null param for current folder */
$root_path = realpath( '' );

/* Initialize archive object */
$zip = new ZipArchive;
$zip_open = $zip->open( $zip_file, ZipArchive::CREATE );

/* Create recursive files list */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator( $root_path ),
    RecursiveIteratorIterator::LEAVES_ONLY
);

/* For each files, get each path and add it in zip */
if( !empty( $files ) ){

    foreach( $files as $name => $file ) {

        /* get path of the file */
        $file_path = $file->getRealPath();

        /* only if it's a file and not directory, and not excluded. */
        if( !is_dir( $file_path ) && !in_array( $file_path, $exclude_files ) ){

            /* get relative path */
            $file_relative_path = str_replace( $root_path, '', $file_path );

            /* Add file to zip archive */
            $zip_addfile = $zip->addFile( $file_path, $file_relative_path );
        }
    }
}

/* Create ZIP after closing the object. */
$zip_close = $zip->close();

UNZIP Files using PHP

You can unzip file to the same folder using this code:

/**
 * Unzip File in the same directory.
 * @link http://stackoverflow.com/questions/8889025/unzip-a-file-with-php
 */
$file = 'file.zip';

$path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
    $zip->extractTo( $path );
    $zip->close();
    echo "WOOT! $file extracted to $path";
}
else {
    echo "Doh! I couldn't open $file";
}

Other Alternative to ZIP / UNZIP File

Actually, if using cPanel you can easily create zip and unzip files using cPanel File Manager.

cpanel-zip-unzip-file-manager

I hope this tutorial is useful for you who need a simple way to move files from server to server.

52 Comments

  1. Yuri

    You are a GENIUS.
    thanks, amazing, I am founding this clean solutions since two days!!!

    bye Yuri

  2. Sheuly Debnath

    I have problem with extract a zip file and put it to another server.
    $local_file = ‘project/files/timber_HTML.zip’;
    but where i want to extract the zip file..
    $remote_file = ‘vistacart/’;
    i have ftp username,password.

    how can do that?please help me.

  3. siyaz

    But according to my knowledge you don’t have to use ftp to transfer a zip file you can just use this
    FILE_PUT_CONTENTS(“destination_zip_file.zip”,FILE_GET_CONTENTS(“http://domain.com/source_zip_file.zip”));

    anyone who needs someone to help him or her with a website contact me I need cash

  4. Marc

    Hi, looks great. I was wondering if this could be used to send log files, that are not in my root folder but at the source of my server (web/lamp0/var/log/apache/access.log), to an extern website like loggly.com or logz.io (http://listener.logz.io). I’m on a shared hosting provider that doesn’t allow to install a script via ssh. So logz.io said i could make a php script to retrieve the log file and send them to there link (http://listener.logz.io:8021………..). I could put a cron job on it to automatically do it every day 😉 Thanks in advance for your response.

  5. Kyle

    I’m a bit confused on the destination/remote directory structure. Where is the path relative to? I’ve seen some with directories before the file name and some like yours without. I’m also using a canvas base64 data as the handle but not sure where the issue is given the poor error response from ftp_fput. Any help is appreciated.

    • David

      it’s relative to the php file.
      the file where you write the code /access it.
      but if you prefer in other dir/make sure it will be in the right dir, use full path.
      I’m not sure about your base 64 data.

  6. Joe

    How big can this file be, I need to move a 10GB zip from bluehost to godaddy. is it possible?

    • David

      Actually I don’t know the limit. depends on your server/connection. You probably have to trial-and-error and probably separate your files into smaller files.

  7. Sajjad

    Great and easy tutorial. I am using this snippet for create zip file.
    function Zip($source, $destination)
    {
    if (!extension_loaded(‘zip’) || !file_exists($source)) {
    return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
    }

    $source = str_replace(‘\\’, ‘/’, realpath($source));

    if (is_dir($source) === true)
    {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
    $file = str_replace(‘\\’, ‘/’, realpath($file));

    if (is_dir($file) === true)
    {
    $zip->addEmptyDir(str_replace($source . ‘/’, ”, $file . ‘/’));
    }
    else if (is_file($file) === true)
    {
    $zip->addFromString(str_replace($source . ‘/’, ”, $file), file_get_contents($file));
    }
    }
    }
    else if (is_file($source) === true)
    {
    $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
    }

    Thanks for sharing with us.

  8. Chad

    Hi David,

    This is great – is there a way to automate this further by scheduling the script to run every few days? In my case, there is a zip file on another server that is updated every few days, and I want to schedule a download of it to my server, have the file unzipped, and overwrite the previous unzipped file at the same path.

    I’m not sure why the file is zipped in the first place, it is only one file (an XML file). Thanks!

  9. Purushothaman J

    Awesome Script. it happened like a blaze. thank you David. the code is really awesome.

  10. Ike Ten

    Great Code. Did all the heavy lifting using just the first code .Just make sure files.zip have same name at source and destination.
    The only edit you need to make is to the “$remote_file_url = ‘http://origin-server-url/files.zip’;” Just replace http://origin-server-url/files.zip with your source url. U are are now ready to roll!
    Thank you.

  11. Shakti Das

    Nice post David..
    Can u pls tell me about size i am trying to move files approx 2Gb per file will it work through the php and what will be the speed.

  12. srini

    i need to download ‘all video files in a folder (from my hosting)’ TO my ‘local hard disk folder automatically’. Can u help me out. thanks in advance

  13. Mudi

    when i upload unzip script through ftp credentials and php code on remote server this is not working. when file uploaded suddenly it becomes blank.

    i dont know what the hell is that …

    any suggestion plz

  14. cn arabia

    Hi,

    I was looking for a code php to redirect a log file coming from a GPS box to my server through a php file (upload.php) but i don’t know how to make the script

  15. vipin

    Hi,
    Warning: ftp_get() [function.ftp-get]: Can’t open filename.
    please help me..

  16. Petrus

    Hi David,

    After searching for years something that is FREE and REALLY works, I happen to stumble on your article.

    I used your PHP COPY example and it was perfect! It was so much faster than downloading and re-uploading.

    Thank you so much!!!!!!

Comments are closed.