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:
// Copy method
$fullPath = "http://serverurl";
$path_parts = pathinfo($fullPath);
$my_file = urldecode($path_parts['basename']);
 echo "Download successful";
 echo "Unable to download file";
Method 2:
// Curl method
$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);
echo (filesize($file) > 0)? "Download successful": "Unable to download file";

Method 3:
// 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);

Permanent link to this article:

Leave a Reply

Your email address will not be published.