skip to content

PHP: cURL alternative to file_get_contents over HTTP

 Tweet0 Tweets


The http_get_contents function





Sample Usage



Improved Functionality



<?PHP // Original JavaScript code by Chirp Internet: // Please acknowledge use of this code by including this header. function http_get_contents($url, Array $opts = []) { $ch = curl_init(); if(!isset($opts[CURLOPT_TIMEOUT])) { curl_setopt($ch, CURLOPT_TIMEOUT, 5); } curl_setopt($ch, CURLOPT_URL, $url); if(is_array($opts) && $opts) { foreach($opts as $key => $val) { curl_setopt($ch, $key, $val); } } if(!isset($opts[CURLOPT_USERAGENT])) { curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['SERVER_NAME']); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); if(FALSE === ($retval = curl_exec($ch))) { error_log(curl_error($ch)); } return $retval; } ?>

Passing a non-blank User Agent string is good practice, and sometimes required to avoid your requests being blocked. See our article on parsing robots.txt for some examples.

Some Examples



Fetching and parsing the Apache response headers for an HTTP request:

<?PHP function read_header($ch, $string) { // function to receive and process the response headers } $tmp = http_get_contents($url, [ CURLOPT_HEADERFUNCTION => __NAMESPACE__ . '\read_header', CURLOPT_NOBODY => TRUE ]); ?>




Send a message to The Art of Web:


<- copy the digits from the image into this box

press <Esc> or click outside this box to close

Post your comment or question