I would like to get the redirect URL using cURL in PHP.
The code I’m currently using is:
public function request($uri = null)
{
$redirects = 0;
if ($uri === null) {
$uri = $this->getUri();
}
while ($redirects < $this->options['maxredirects']) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_USERAGENT, $this->options['useragent']);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->options['timeout']);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
$this->addResult($result, $info);
if (floor($info['http_code'] / 100) != 3) {
return null;
}
$redirects++;
}
}
I don’t what to use CURLOPT_FOLLOWLOCATION, because (correct me if wrong) that automatically follows the redirect.
I was hoping it would have been in curl_getinfo(), but it isn’t. It looks like I have to enable CURLOPT_HEADER and parse the header to get the ‘next’ URL.
- Is this correct?
- If “Yes” how would I be able to parse the header? E.g. can I safely
explode()the string on\nand find the item which starts withLocation:?
Yes, you set
CURLOPT_HEADERtotrueand then parse the string by exploding it with\r\n.There is also other ways, but not sure if they are valid in your case –
get_headers()and http://www.php.net/manual/en/function.http-head.php