Joel Verhagen

a computer programming blog

PHP cURL Function for Dummies and Lazy Persons

If you've ever used PHP with a web API (such as Facebook's shiny new Graph API), you've probably run in PHP's cURL bindings. This is the basic function I use to download the contents of a URL. It is pretty usable (handle GET and POST queries) and you can easily pass query parameters and headers you want to include in the request.

For those naughty screen scrapers out there, this PHP function could help you out a little bit.

Edit 2010-12-19: My function was not handling uploads, so I made a quick change. It's working fine now.

<?php
function curlContents($url, $method = 'GET', $data = false, $headers = false, $returnInfo = false) {    
    $ch = curl_init();
    
    if($method == 'POST') {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        if($data !== false) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
    } else {
        if($data !== false) {
            if(is_array($data)) {
                $dataTokens = array();
                foreach($data as $key => $value) {
                    array_push($dataTokens, urlencode($key).'='.urlencode($value));
                }
                $data = implode('&', $dataTokens);
            }
            curl_setopt($ch, CURLOPT_URL, $url.'?'.$data);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    if($headers !== false) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    $contents = curl_exec($ch);
    
    if($returnInfo) {
        $info = curl_getinfo($ch);
    }

    curl_close($ch);

    if($returnInfo) {
        return array('contents' => $contents, 'info' => $info);
    } else {
        return $contents;
    }
}

Here is a little documentation on the arguments

  • url, the URL you would like to fetch.
  • method (optional), defaults to "GET". You can also pass "POST" for a POST request.
  • data (optional), can be encoded query parameters (i.e. "foo1=bar1&foo2=bar2") or an associative array of the data you want to pass as parameters (i.e. array("foo1" => "bar1", "foo2" => "bar2")).
  • headers (optional), an array of header values (i.e. array("Content-type: image/png"))
  • returnInfo (optional), defaults to false whether or not to return information about the request. If you specify true, then its return is formatted like this: array('contents' => $contents, 'info' => $info).