PHP: how to save a remote file using CURL


How to save a remote file using CURL?

<?php

/**
 * @author tutorialspots.com
 * @copyright 2018
 */
 
function saveRemoteFile($url, $filename) {
 
    set_time_limit(0);
    
    # Open the file 
    $fp = fopen($filename, 'w+');
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, "YOUR_USER_AGENT");  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); # optional
    curl_setopt($ch, CURLOPT_TIMEOUT, -1);  
    curl_setopt($ch, CURLOPT_VERBOSE, false); # Set to true to see all the innards
    
    # Only if you need to bypass SSL certificate validation
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    # Assign a callback function to the CURL Write-Function
    curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($cp, $data) use ($fp) {     
        $len = fwrite($fp, $data);
        return $len;
    });
    
    # Exceute the download - note we DO NOT put the result into a variable!
    curl_exec($ch);
    
    # Close CURL
    curl_close($ch);
    
    # Close the file pointer
    fclose($fp);
}
 
?>

You can read more about CURLOPT_WRITEFUNCTION in this article:
PHP: Example of usage CURLOPT_WRITEFUNCTION

No comments yet.

Leave a Reply