This is a short guide on how to force PHP’s cURL functions to follow a HTTP redirect. By default, cURL will not follow any redirect headers that are sent by the server.
301 Moved.
If you send a cURL request that doesn’t follow redirects, you may end receiving the following response from the server:
301 Moved. The document has moved here.
Note that you might also receive a 302 header. This all depends on the server and the URL that you are sending a request to.
Take the following PHP example:
//The URL of the page that we want to retrieve. $url = 'http://google.com'; //Initiate cURL and pass it the URL we want to retrieve. $ch = curl_init($url); //Tell cURL to return the output as a string. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Execute the cURL request and return the output to a string. $response = curl_exec($ch); //Print out the response to the browser. echo $response;
The above code will output “301 Moved” response because Google has a 301 redirect on the URL in question and our cURL client has not been configured to follow it.
PHP and the CURLOPT_FOLLOWLOCATION option.
This is where the CURLOPT_FOLLOWLOCATION option comes in useful. This option tells the cURL client that it should automatically follow any redirects specified in the “Location:” header. Hence the name “follow location”.
In PHP, you can use this option like so:
//Tell cURL that it should follow any redirects. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
If you add the line above to our original code, you will see that our cURL client now follows Google’s 301 redirect.
Using the CURLOPT_MAXREDIRS option.
If your cURL client follows redirects, then it is a good idea to also use the CURLOPT_MAXREDIRS option. This allows us to specify the maximum number of redirects that we should follow before stopping. If we do not set this option, then a simple server misconfiguration could kill our client by sending it too many redirect headers. The CURLOPT_FOLLOWLOCATION option is recursive, which means that you could get stuck in an endless redirect loop.
An example using PHP:
//Tell cURL that it should only follow 3 redirects at most. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
The PHP code above tells cURL that it should only follow 3 redirects. If a 4th redirect is encountered, a “CURLE_TOO_MANY_REDIRECTS” error will be thrown.