I just came across a situation where I needed to transfer files from one server to another every time a new entry gets created. I had status variables to inform new entry data, I used CURL and PHP file’s to get it done.

This method is quite useful, not only in the situations like mine but also when you want user’s to be able to upload images or files from URL.

This is similar to uploading files, but a little more straight forward. It allows you to download the file directly to your desired location where as in upload you have to move it from temporary location after upload. Not a big deal though. But it is handy for user on low bandwidth & file is available else where online.

How it works

The idea here is to open an empty file in server fill it with contents form remote server / remote location. Now you have file on memory, save the file in memory to disk you have it.


function downloadfile ( $url ) {

       if ( empty ( $url ) ) {
            return false; // In case no url is passed
        }

	$filename = basename($url); 
        // basename returns the name + extension of the file removing other elements ( Path to file, http:// etc )
	$file_temp_location = '  / ' . $filename;  
        // Location to save file on your server 
	$ch = curl_init(url);
	$fp = fopen($file_temp_location, 'wb');
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_exec($ch);
	curl_close($ch);
	fclose($fp);
}

This will get the file to your server, but that is not it along with file it can bring in trouble as well so It’s recommended that you check the file size before the executing the transfer. Over sized file can get your server to overload so at least do a verification for file size before downloading it.

 //Size will be returned in bytes
function filesize($file){
	if( empty( $file ) ) {
            return false; // In case no url is passed
        }
	$ch = curl_init( $file );
	curl_setopt($ch, CURLOPT_NOBODY, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	
        $filedata = curl_exec($ch);
	curl_close($ch);
	
	if (preg_match('/Content-Length: (d+)/', $filedata, $metadata)) {
		$size = (int)$metadata[1];
		return $size;
	} else {
		return false;
                // File corrupt or not available at remote location 
        }
}

In here we will request the metadata and evaluate the file size without downloading to your server, you can get in trouble if a user links to an over sized file. This can also check if the file exist.