Tabassum Ali
Tabassum Ali

Reputation: 43

copy file from one server to another programmatically in php

I've hosted my all code files on one server whose domain is like example.com and I'm at one of those html pages. I want some files of example.com to move on another server whose domain is like example2.com. I've searched through Internet but I couldn't find any good solution. Please tell me is this possible without FTP client or without browser where we upload files manually. Or is there any way to submit file from HTML form from one server to another like if on action we'll write

<form action="http://example2.com/action_page.php">

Any help would be much appreciated.

Upvotes: 4

Views: 17459

Answers (4)

user12143633
user12143633

Reputation: 29

    <?php
/* Source File URL */
$remote_file_url = 'http://origin-server-url/files.zip';
  
/* New file name and path for this new 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! Thanks Munshi and OBOYOB! success to copy $file...\n";
}
?>

Upvotes: -1

Sola Alagbe
Sola Alagbe

Reputation: 1

You can exchange files between servers by also using zip method. You own both servers so you shouldn't have security issues.

On the server that hosts the file or folder you want, create a php script and create a cron job for it. Sample code below:

<?php
/**
 * ZIP All content of current folder

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

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

/* Path of current folder, need empty or null param for current folder */
$root_path = realpath( '' ); //or $root_path = realpath( 'folder_name' ); if the file(s) are in a particular folder residing in the root

/* 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();
?>

Create another php script and cron job on the server to receive the copy as below:

/**
* Transfer Files Server to Server using PHP Copy
*
*/ /* Source File URL */
$remote_file_url = 'url_of_the_zipped';

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

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

/* Add notice for success/failure */ 
if( !$copy ) {
echo "Failed to copy $file...\n"; }
else{
echo "Copied $file successfully...\n"; }
$file = 'myfiles.zip';
$path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
$zip->extractTo( $path );
$zip->close();
echo "$file extracted to $path"; }
else {
echo "Couldn't open $file";
}
?>

Voila!

Upvotes: 0

JBithell
JBithell

Reputation: 627

If you set the contents of this file: example2.com/action_page.php to:

<?php
$tobecopied = 'http://www.example.com/index.html';
$target = $_SERVER['DOCUMENT_ROOT'] . '/contentsofexample/index.html';

if (copy($tobecopied, $target)) {
    //File copied successfully
}else{
    //File could not be copied
}
?>

and run it, through command line or cron (as you have written a php related question, yet banned use of browsers!) it should copy the contents of example.com/index.html to a directory of your site (domain: example2.com) called contentsofexample.

N.B. If you wanted this to copy the whole website you should place it in a for loop

Upvotes: 4

Satyendra Chaudhary
Satyendra Chaudhary

Reputation: 21

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     = 'http://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 'http://example.com/myproxy.php?file=filename.extension&passkey=my-secret-key'.

Upvotes: 2

Related Questions