note 12842 deleted from features.remote-files by irc-html
| From: | irc-html@php.net | Date: | Sat, 19 Jan 2002 20:40:52 +0000 |
| Subject: | note 12842 deleted from features.remote-files by irc-html | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-25412@lists.php.net to get a copy of this message | ||
Here is a script using fsockopen which *DOES* handle multiple redirects. It will handle the url http://php.net/manual which redirects to http://php.net/manual/ which redirects to http://php.net/manual/en/ (for English-speaking at least). It
worked on all the sites I tried it with except http://www.yahoo.com, although it works for http://www.google.com It also works on sites that do not redirect.
It doesn't encode the url strings though, but thats not hard to add if needed. Feel free to
send me comments/suggestions. Enjoy. Anyone know a better/faster way to do this?
(some is borrowed from the previous post)
<?
//a url that does redirecting twice...
$url = "http://www.php.net/manual";
$maxtries = 5;
$tries = 0;
$redirecting = true;
while ($redirecting && $tries < $maxtries)
{
$tries++;
// get host name and URI from URL, URI not needed though
preg_match("/^(http:\/\/)?([^\/]+)(.+)/i", $url, $matches);
$host = $matches[2];
$uri = $matches[3];
$connection = fsockopen($host ,80,&$errorNumber,&$errorString,10);
if ($connection)
{
//tell server what document we want
fputs ($connection, "GET $url HTTP/1.0");
fputs ($connection, "\r\n");
//Host isn't required by HTTP/1.0 but some sites complain otherwise
fputs ($connection, "Host: $host");
fputs ($connection, "\r\n\r\n");
$headerStart = 0;
$headerEnd = 0;
$redirecting = false;
while (!feof($connection))
{
$currentLine = fgets ($connection, 1024);
if ($headerEnd && $redirecting)
{
break;
}
else if ($headerEnd && !$redirecting)
{
//this is the html from the page
$contents = $contents . $currentLine;
}
else if ( ereg("^HTTP", $currentLine) )
{
//came to the start of the header
$headerStart = 1;
}
else if ( $headerStart && ereg("^[\n\r\t ]*$", $currentLine) )
{
//came to the end of the header
$headerEnd = 1;
}
else
{
//this is the header, if you want it...
if (preg_match("/Location: (.+?)\n/is",$currentLine,$matches) )
{
//redirects are sometimes relative
$newurl = $matches[1];
if (!preg_match("/http:\/\//i", $newurl, $matches) )
{
$url .= $newurl;
}
else
{
$url = $newurl;
}
//extra \r's get picked up sometimes
//i think only with relative redirects
//this is a quick fix.
$url = preg_replace("/\r/s","",$url);
$redirecting = true;
}
}
}
}
else
{
echo "$errstr ($errno)\n";
$url = "";
}
fclose ($connection);
}
print $contents;
?>