In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.
The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects:
<?php
function get_headers_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$r = curl_exec($ch);
$r = split("\n", $r);
return $r;
}
If you do want to follow redirects, you can do something like this:
$go = 1;
$i = 1;
while ($go && $i < 6)
{
$headers = get_headers_curl($url);
$go = getNextLocation($headers);
if ($go)
{
$url = modifyUrl($go);
}
$i++;
}
function getNextLocation($headers)
{
$array = $headers;
$count = count($array);
for ($i=0; $i < $count; $i++)
{
if (strpos($array[$i], "ocation:"))
{
$url = substr($array[$i], 10);
}
}
if ($url)
{
return $url;
}
else
{
return 0;
}
}
?>