Last active
December 27, 2015 09:29
-
-
Save DaSourcerer/7304185 to your computer and use it in GitHub Desktop.
A simple stream-based http client. Good for experimentation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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($output, 'bzip2.decompress', STREAM_FILTER_WRITE); | |
break; | |
case 'gzip': | |
fseek($socket, 10, SEEK_CUR); | |
case 'deflate': | |
stream_filter_append($output, 'zlib.inflate', STREAM_FILTER_WRITE); | |
break; | |
default: | |
die("Unknown content encoding: {$encoding}"); | |
} | |
} | |
while(!feof($socket)) | |
fwrite($output,fread($socket,16384)); | |
fclose($socket); | |
fclose($output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment