Download a Remote File Using PHP and cURL

by damonp on February 3, 2011

in PHP,Snippets

Some years back, I posted a function to download a remote file with PHP. The function was useful when cURL and other URL/remote file functions had been disabled for security reasons. At the time, cURL on PHP was relatively new and many hosting setups didn’t include the cURL PHP module.

Support for PHP-cURL is pretty standard now, so I thought I’d update the the function to use cURL now. In addition, the function no longer returns a buffer containing the file data which can cause memory issues in PHP when dealing with large files. Pass this updated function a remote URL and local file path and it will download the file and save it to the local path.

This function is useful to retrieve remote images, download HTML pages and download any remote files.

<?php
   
    function http_get_file($remote_url, $local_file)    {
       
        $fp = fopen($local_file, 'w');
       
        $cp = curl_init($remote_url);
        curl_setopt($cp, CURLOPT_FILE, $fp);
       
        $buffer = curl_exec($cp);
       
        curl_close($cp);
        fclose($fp);
       
        return true;
    }
?>

Popularity: 14%

More Related Posts

Damon Parker is a freelance sysadmin and web developer in Texas. He specializes in server setup, server security and high performance server configurations. Need help setting up a web server or getting a server back online after a crash or hack? Email Damon

{ 1 comment… read it below or add one }

Katie @ Women's Magazine January 2, 2012 at 7:03 am

I was looking for an answer and couldn’t find it even in Stackoverflow. Finally i landed on your page and it worked. Thanks you saved many hours

Cheers :)

Reply

Leave a Comment

Previous post:

Next post: