Simple cURL example

A simple example on how to use the CURL module.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
04/27/2006

Updated:
07/23/2007

Tags:
, ,


function DownloadUrl($Url){
 
    // is curl installed?
    if (!function_exists('curl_init')){ 
        die('CURL is not installed!');
    }
 
    // create a new curl resource
    $ch = curl_init();
 
    /*
    Here you find more options for curl:
    http://www.php.net/curl_setopt
    */
 
    // set URL to download
    curl_setopt($ch, CURLOPT_URL, $Url);
 
    // set referer:
    curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
 
    // user agent:
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
 
    // remove header? 0 = yes, 1 = no
    curl_setopt($ch, CURLOPT_HEADER, 0);
 
    // should curl return or print the data? true = return, false = print
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
    // timeout in seconds
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
 
    // download the given URL, and return output
    $output = curl_exec($ch);
 
    // close the curl resource, and free system resources
    curl_close($ch);
 
    // print output
    return $output;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

sandeep July 15, 2010 at 04:59
thanks alot, setting up all _setopt is compulsory ??
Natalie April 07, 2010 at 19:09
Thank you.
Sachin February 05, 2010 at 14:15
Good Article
Can i login with curl or post form values using curl.
Sam January 08, 2010 at 17:22
Thanks for example.
Niranjan: you can use eval(), but it hase some security issues...
john December 10, 2009 at 16:25
Very helpful! Thank you!
Craig R Morton August 17, 2009 at 12:45
Many thanks, this worked well for me to check if I had cURL setup correctly on my machine. Perfect for a PHP beginner. :-)
Niranjan Ramakrishnan July 25, 2009 at 11:48
I'm trying to use curl to replace the includes in my code. I've run into a problem. Suppose I am trying to include foreign.php into my fiile native.php. Assume that foreign.php contains a variable $xyz. The include works fine, but I am unable to use $xyz inside native.php. In our system, register_globals is turned off. What is the way around this?
Chanon February 11, 2009 at 13:03
Thanks mate

This code and comment is really clear and useful for the beginner like me.
Great job!