How to download file from remote URL in PHP

There are many ways in PHP to download file from the remote server. We can use php functions like copy, file_get_content, fopen, fsockopen & Curl to download the remote files. For your reference here I have explained about copy, fopen and Curl method, I have choosen these methods based on simplify and easily everyone can understand & use it. We can download large file with minimum memory usages.

Method 1:
[php]
// Copy method
$fullPath = "http://serverurl";
$path_parts = pathinfo($fullPath);
$my_file = urldecode($path_parts['basename']);
if(@copy($fullPath,$my_file))
 echo "Download successful";
else
 echo "Unable to download file";
[/php]
Method 2:
[php]
// Curl method
set_time_limit(0);
$url ="http://serverurl";
$file = basename($url);
// Open file to write
$fp = fopen($file, 'w+');
$ch = curl_init($url);
// increase timeout to download big file
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
echo (filesize($file) > 0)? "Download successful": "Unable to download file";
[/php]



Method 3:
[php]
// File method
$fullPath = "http://serverurl";
$path_parts = pathinfo($fullPath);
$handle = @fopen($fullPath, "r");
$data = "";
while(!feof($handle)) {
 $data .= fread($handle, 2048);
}
fclose ($handle);
$my_file = urldecode($path_parts['basename']);
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file);
fwrite($handle, $data);
fclose ($handle);
[/php]

Permanent link to this article: https://blog.openshell.in/2014/03/how-to-download-file-from-remote-url-in-php/

Leave a Reply

Your email address will not be published.