Thursday, 25 February 2016
Download File from Remote Server with PHP
On my previous post I was shown how we can get a remote file size without download it in php. Today I am going to show you how can we download a file from remote server with php.
There are many ways in PHP to download file from remote server. We can use php functions like copy, file_get_content, fopen, fsockopen to download remote files. These functions are well but today we will use curl to download file. Because it the advanced way to working with remote resources.We can download large file with minimum memory usages in this way.
getHeaders Function
This function gets all header information before downloading a file. This function will help you to know file is exist or not and filesize
download Function
This function download file form remote server.
Usages
There are many ways in PHP to download file from remote server. We can use php functions like copy, file_get_content, fopen, fsockopen to download remote files. These functions are well but today we will use curl to download file. Because it the advanced way to working with remote resources.We can download large file with minimum memory usages in this way.
getHeaders Function
This function gets all header information before downloading a file. This function will help you to know file is exist or not and filesize
/**
* Get Headers function
* @param str #url
* @return array
*/
function getHeaders($url)
{
$ch = curl_init($url);
curl_setopt( $ch, CURLOPT_NOBODY, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_HEADER, false );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
curl_exec( $ch );
$headers = curl_getinfo( $ch );
curl_close( $ch );
return $headers;
}
download Function
This function download file form remote server.
/**
* Download
* @param str $url, $path
* @return bool || void
*/
function download($url, $path)
{
# open file to write
$fp = fopen ($path, 'w+');
# start curl
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
# set return transfer to false
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
# increase timeout to download big file
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
# write data to local file
curl_setopt( $ch, CURLOPT_FILE, $fp );
# execute curl
curl_exec( $ch );
# close curl
curl_close( $ch );
# close local file
fclose( $fp );
if (filesize($path) > 0) return true;
}
Usages
$url = 'http://path/to/remote/file.jpg';
$path = 'uploads/file.jpg';
$headers = getHeaders($url);
if ($headers['http_code'] === 200 and $headers['download_content_length'] < 1024*1024) {
if (download($url, $path)){
echo 'Download complete!';
}
}
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment