Tags
Asked 2 years ago
9 Jun 2021
Views 271
eclipse-learner

eclipse-learner posted

Download file from URL using CURL

Download file from URL using CURL
dilip

dilip
answered Apr 26 '23 00:00

To download a file from a URL using cURL in PHP, you can use the CURLOPT_RETURNTRANSFER and CURLOPT_BINARYTRANSFER options to get the file contents as a string, and then save the string to a file using file handling functions.

Here's an example:



$url = "https://www.example.com/image.jpg";
$filename = "image.jpg";

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url); // URL to download from
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return response as string
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // return raw output
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects

// Execute cURL session
$response = curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Save the file to disk
$fp = fopen($filename, "wb");
fwrite($fp, $response);
fclose($fp);

In this example, we specify the URL of the file to download and the filename to save the file as. We set the CURLOPT_RETURNTRANSFER , CURLOPT_BINARYTRANSFER , and CURLOPT_FOLLOWLOCATION options as before.

After executing the cURL session, we save the response as a file using file handling functions. We open a file handle using fopen (), write the contents of the response using fwrite (), and close the file handle using fclose ().

Note that if the file is very large, it may be better to use the CURLOPT_FILE option to write the response directly to a file without loading it into memory. Here's an example:



$url = "https://www.example.com/bigfile.zip";
$filename = "bigfile.zip";

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url); // URL to download from
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return response as string
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // return raw output
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects
curl_setopt($ch, CURLOPT_FILE, fopen($filename, 'w'));

// Execute cURL session
curl_exec($ch);

// Check for errors
if(curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

In this example, we use the CURLOPT_FILE option to open a file handle with the fopen () function and write the response directly to the file without loading it into memory.
Post Answer