note 81509 deleted from function.fsockopen by danbrown
| From: | danbrown@php.net | Date: | Sun, 20 Jul 2008 19:21:50 +0000 |
| Subject: | note 81509 deleted from function.fsockopen by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-142290@lists.php.net to get a copy of this message | ||
Note Submitter: Anonymous
----
Of course, copy() is the ultimate download function, but it saves the data in a file, and probably
you can use fopen() to get it as a string, but this function double checks everything, and has
support for $http_response_header and
unlike file_get_contents(), it works on php 4.0.0
(Oh, and by the way, if you use it in another function like i do, don't forget to declare
$http_response_header as global, or you won't be able to see the variable, even though you
called it in the function)
<?php
if(!function_exists("stripos")){
function stripos($str, $needle, $offset=0){
return strpos(strtolower($str),strtolower($needle),$offset);
}/* endfunction stripos */
}/* endfunction exists stripos*/
if(!function_exists("download")){
function download($uri, $port = 80){
if(!is_int($port))$port = 80;
$uri = strtr( strval($uri), array("http://" =>
"", "https://" => "ssl://",
"\\" => "/", "//" => "/") );
if( ( $protocol = stripos($uri, "://") ) !== FALSE ){
if( ( $domain_pos = stripos($uri, "/", ($protocol + 3)) ) !== FALSE ){
$domain = substr($uri, 0, $domain_pos);
$file = substr($uri, $domain_pos);
}
else{
$domain = $uri;
$file = "/";
}
}
else{
if( ( $domain_pos = stripos($uri, "/") ) !== FALSE ){
$domain = substr($uri, 0, $domain_pos);
$file = substr($uri, $domain_pos);
}
else{
$domain = $uri;
$file = "/";
}
}
$fp = fsockopen($domain, $port, $errno, $errstr, 30);
if(!$fp){
return FALSE;
}
else{
$out = "GET " . $file . " HTTP/1.1\r\n";
$out .= "Host: " . $domain . "\r\n";
$out .= "Connection: Close\r\n\r\n";
$response = "";
fwrite($fp, $out);
while (!feof($fp)) {
$response .= fgets($fp, 128);
}
fclose($fp);
global $http_response_header;
$http_response_header = array();
if( stripos($response, "\r\n\r\n") !== FALSE ){
$hc = explode("\r\n\r\n", $response);
$headers = explode("\r\n", $hc[0]);
if(!is_array($headers))$headers = array();
foreach($headers as $key => $header){
$a = "";
$b = "";
if( stripos($header, ":") !== FALSE ){
list($a, $b) = explode(":", $header);
$http_response_header[trim($a)] = trim($b);
}
}
return end($hc);
}
else if( stripos($response, "\r\n") !== FALSE ){
$headers = explode("\r\n", $response);
if(!is_array($headers))$headers = array();
foreach($headers as $key => $header){
if( $key < ( count($headers) - 1 ) ){
$a = "";
$b = "";
if( stripos($header, ":") !== FALSE ){
list($a, $b) = explode(":", $header);
$http_response_header[trim($a)] = trim($b);
}
}
}
return end($headers);
}
else{
return $response;
}
}
}/*endfunction download*/
}/*endif no function download*/
?>