Php move file from one server to another

There are still 2 possible ways which can used to copy your files from another server.

-One is to remove your .htaccess file from example.com or allow access to all files[by modifying your .htaccess file]. -Access/Read those files via their respective URLs, and save those files using 'file_get_contents[]' and 'file_put_contents[]' methods. But this approach will made all files accessible to other people too.

            $fileName       = 'filename.extension';
            $sourceFile     = '//example.com/path-to-source-folder/' . $fileName;
            $targetLocation = dirname[ __FILE__ ] . 'relative-path-destination-folder/' + $fileName;

            saveFileByUrl[$sourceFile, $targetLocation];

            function saveFileByUrl [ $source, $destination ] {
                if [function_exists['curl_version']] {
                    $curl   = curl_init[$fileName];
                    $fp     = fopen[$destination, 'wb'];
                    curl_setopt[$ch, CURLOPT_FILE, $fp];
                    curl_setopt[$ch, CURLOPT_HEADER, 0];
                    curl_exec[$ch];
                    curl_close[$ch];
                    fclose[$fp];
                } else {
                    file_put_contents[$destination, file_get_contents[$source]];
                }
            }

Or you can create a proxy/service on example.com to read a specific file after validating a pass key or username/password combination[whatever as per your requirement].

            //In myproxy.php
            extract[$_REQUEST];
            if [!empty[$passkey] && paskey == 'my-secret-key'] {
                if [!empty[$file] && file_exists[$file]] {
                    if [ob_get_length[]] {
                        ob_end_clean[];
                    }
                    header["Pragma: public"];
                    header[ "Expires: 0"];
                    header[ "Cache-Control: must-revalidate, post-check=0, pre-check=0"];
                    header[ 'Content-Type: ' . mime_content_type[$file] ];
                    header[ "Content-Description: File Transfer"];
                    header[ 'Content-Disposition: attachment; filename="' . basename[ $file ] . '"' ];
                    header[ "Content-Transfer-Encoding: binary" ];
                    header[ 'Accept-Ranges: bytes' ];
                    header[ "Content-Length: " . filesize[ $file ] ];
                    readfile[ $file ];
                    exit;
                } else {
                    // File not found 
                }
            } else {
                //  You are not authorised to access this file.
            }

you can access that proxy/service by url '//example.com/myproxy.php?file=filename.extension&passkey=my-secret-key'.

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 //destination-url/copy-files.php and in copy-files.php you add this php code:

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

/* Source File URL */
$remote_file_url = '//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 //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 = ''; /* 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 //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 = ''; /* 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 //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 //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.

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

How do I move a file from one server to another in php?

Kickstart HTML, CSS and PHP: Build a Responsive Website $file = "file_name. jpg"; $destination = fopen["ftp://username:password@example.com/" . $file, "wb"]; $source = file_get_contents[$file]; fwrite[$destination, $source, strlen[$source]]; fclose[$destination]; The image needs to be transferred to an FTP server.

How do I transfer files from one server to another?

To transfer files between 2 Windows servers, the traditional way is to use FTP desktop app as a middle-man. You need to download Filezilla or other FTP desktop tool, configure and use it to upload or download files between two remote servers.

How do you move a file in php?

Moving files in PHP is as simple as using a single function – rename["SOURCE. FILE", "FOLDER/TARGET. FILE"] . Yes, there is no move file function in PHP, and we literally “rename” a file into another folder.

How do I move a folder to another directory in php?

Linked.
Move folders and files to a folder..
Using scandir[] to find folders in a directory [PHP].
Copy all files and folder from one directory to another directory PHP..

Chủ Đề