How to Follow Redirects with cURL for CLI or PHP

0 min read 196 words

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.

Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags