note 90434 modified in function.get-headers by danbrown

From: Date: Wed, 22 Apr 2009 21:13:03 +0000
Subject: note 90434 modified in function.get-headers by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153595@lists.php.net to get a copy of this message
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; } } ?> --was-- 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: 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; } } http://php.net/manual/en/function.get-headers.php

« previous php.notes (#153595) next »