Skip to content

Instantly share code, notes, and snippets.

@pmoust
Forked from DaSourcerer/httpget
Last active Dec 27, 2015
Embed
What would you like to do?
#!/usr/bin/php
<?php
$scheme='tcp';
$host='www.kernel.org';
$port=80;
$path='/';
if(isset($argv[1])) {
$parsedUrl=parse_url($argv[1]);
$scheme=($parsedUrl['scheme']=='https')?'ssl':'tcp';
$port=isset($parsedUrl['port'])?$parsedUrl['port']:getservbyname($parsedUrl['scheme'],'tcp');
$host=$parsedUrl['host'];
if(isset($parsedUrl['path']))
if($path{0}!='/')
$path='/'.$path;
else
$path='/';
if(isset($parsedUrl['query']))
$path.='?'.$parsedUrl['query'];
}
if(($socket=@stream_socket_client("$scheme://$host:$port", $errno, $errstr, 1, STREAM_CLIENT_CONNECT))===false)
die("Error creating stream ({$errno}): {$errstr}");
$headers=array(
"GET {$path} HTTP/1.1",
"Host: {$host}:{$port}",
'Accept: text/html, application/xhtml+xml, text/*',
'Accept-Language: *',
'Accept-Encoding: gzip, deflate, bzip2',
'TE: chunked',
'User-Agent: Mozilla/5.0 (compatible)',
"Connection: close\r\n\r\n",
);
fwrite($socket,implode("\r\n",$headers));
$chunked=false;
$encoding=false;
while(($line=fgets($socket))!==false && !feof($socket) && trim($line)!='') {
if(stripos($line, 'Content-Encoding')===0)
$encoding=trim(end(explode(':', $line, 2)));
elseif(stripos($line, 'Transfer-Encoding')===0)
$chunked=(strcasecmp(trim(end(explode(':', $line, 2))),'chunked')===0);
echo $line;
}
echo PHP_EOL;
$output=fopen('php://output','w');
if($chunked)
stream_filter_append($output, 'dechunk', STREAM_FILTER_WRITE);
if($encoding) {
switch($encoding) {
case 'identity':
break;
case 'bzip2':
stream_filter_append($socket, 'bzip2.decompress', STREAM_FILTER_WRITE);
break;
case 'gzip':
fseek($socket, 10, SEEK_CUR);
case 'deflate':
stream_filter_append($socket, 'zlib.inflate', STREAM_FILTER_WRITE);
break;
default:
die("Unknown content encoding: {$encoding}");
}
}
stream_copy_to_stream($socket, $output);
fclose($socket);
fclose($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment