|
Get a 25% off coupon to use on any of our website scripts! - Subscribe to our Newsletter now!
|
Following 301 + 302 Redirects With cURL + PHPPosted 2011-02-06 in Scripts
cURL, the PHP Client URL library, is extremely useful for handling URL requests within PHP. One of the shortcomings that I have encountered is properly dealing with 301 and 302 redirects. In this post I will share some code that checks for 301 and 302 redirects. Normally you would set the following cURL option to follow a redirect: curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); Unfortunately this doesn't always work. Either due to a server misconfiguration or a 301 response that is ignored, sometimes cURL will just spit out a "1" instead of the contents of the page you're fetching. The code below solves the problem before you even make a request. Pass get_furl() the URL to retrieve, and it will check the server reponse headers for a 301 redirect or 302 redirect HTTP code. If one is found, this function will extract the proper new URL and return it for you. Then you can continue with your cURL request knowing that any 301 or 302 redirect has been resolved. function get_furl($url)
{
$furl = false;
// First check response headers
$headers = get_headers($url);
// Test for 301 or 302
if(preg_match('/^HTTP\/\d\.\d\s+(301|302)/',$headers[0]))
{
foreach($headers as $value)
{
if(substr(strtolower($value), 0, 9) == "location:")
{
$furl = trim(substr($value, 9, strlen($value)));
}
}
}
// Set final URL
$furl = ($furl) ? $furl : $url;
return $furl;
}
Just save the function as a new include to your library, or drop it in the current script to use it. Here is an example using the function provided above in a cURL request to fetch the full contents of a page. $url = get_furl('http://www.example.com/');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
$contents = curl_exec($ch);
curl_close($ch);
echo $contents;
Another advantage of using this method is that you don't need to use CURLOPT_HEADER option in your cURL request, which may be a nuisance if you just want the HTML response. Hope this helps!
|
SearchPopular Articles
SubscribeSubscribe via RSS Stay current with Scriptalicious news and subscribe in your favorite RSS reader. Subscribe via EmailGet the latest Scriptalicious news delivered to your inbox. Tag Cloudseo guides seo scripts scriptalicious seo tools forums PageRank SEO services content development apache htaccess mod_rewrite scripts webmaster google yahoo JavaScript XMLHttpRequest php contest software website list facebook ebook pagerank bing backlink rankings tool turnkey checker alexa themes marketing tinymce wysiwyg browser rank script tools legal trademark infringement mysql social web social networking advertising google plus plus one backlinks |
77 powerful SEO scripts for under $100. |
Real-time Backlink Rank Checker script. |