How to Follow Redirects with cURL for CLI or PHP

Let’s take a really common example. Say we want to follow redirects with cURL for google.com. It is common to curl follow redirect a URL.

Follow Redirects with cURL in the CommandLine

If you navigate directly to google in the command-line using curl, you will be taken to a 301 redirect URL.

curl google.com

#<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
#<TITLE>301 Moved</TITLE></HEAD><BODY>
#<H1>301 Moved</H1>
#The document has moved
#<A HREF="http://www.google.com/">here</A>.
#</BODY></HTML>

This makes sure that you follow the proper canonical URL as set by the particular website in question.

We can easily curl follow redirect to the end redirection by adding in the -L flag.

curl -L google.com

#<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en">...

Follow Redirects with cURL in PHP

If you’re doing this in PHP and want to find out where the redirected page goes, instead of actually going there yourself, you can do something like this to curl follow redirect:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
}

This is particularly good for following URLs shorteners, such as the likes of Bit.ly and TinyURL to name only two.

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments