Skip to content

Instantly share code, notes, and snippets.

@bgrimes
Created June 5, 2012 16:24
Show Gist options
  • Save bgrimes/2876054 to your computer and use it in GitHub Desktop.
Save bgrimes/2876054 to your computer and use it in GitHub Desktop.
Curl get contents
<?php
/**
* Curl get contents instead of file_get_contents.
*
* @param string The URL to grab contents of
* @param array Post data to send to the url, empty if not desired
* @param mixed Bool false if no desired verbose output, string of filename to write to if verbose output desired
* @param mixed False if referer not desired, string if you wish to set a referrer url
* @param mixed False if no cookie desired, string to set the cookie filepath
* @param bool Whether or not to set the return transfer option on
* @return mixed String of data retrieved from the url if successful, boolean false if not successful
*/
function curl_get_contents($url,array $post_data=array(),$verbose=false,$ref_url=false,$cookie_location=false,$return_transfer=true)
{
$return_val = false;
$pointer = curl_init();
curl_setopt($pointer, CURLOPT_URL, $url);
curl_setopt($pointer, CURLOPT_TIMEOUT, 40);
curl_setopt($pointer, CURLOPT_RETURNTRANSFER, $return_transfer);
// Set the user agent to Chrome 20.0.1092.0
curl_setopt($pointer, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6");
curl_setopt($pointer, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($pointer, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($pointer, CURLOPT_HEADER, false);
curl_setopt($pointer, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($pointer, CURLOPT_AUTOREFERER, true);
if($cookie_location !== false)
{
curl_setopt($pointer, CURLOPT_COOKIEJAR, $cookie_location);
curl_setopt($pointer, CURLOPT_COOKIEFILE, $cookie_location);
curl_setopt($pointer, CURLOPT_COOKIE, session_name() . '=' . session_id());
}
if($verbose !== false)
{
$verbose_pointer = fopen($verbose,'w');
curl_setopt($pointer, CURLOPT_VERBOSE, true);
curl_setopt($pointer, CURLOPT_STDERR, $verbose_pointer);
}
if($ref_url !== false)
{
curl_setopt($pointer, CURLOPT_REFERER, $ref_url);
}
if(count($post_data) > 0)
{
curl_setopt($pointer, CURLOPT_POST, true);
curl_setopt($pointer, CURLOPT_POSTFIELDS, $post_data);
}
$return_val = curl_exec($pointer);
$http_code = curl_getinfo($pointer, CURLINFO_HTTP_CODE);
if($http_code == 404)
{
return false;
}
curl_close($pointer);
unset($pointer);
return $return_val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment