sockets – PHP Post data with Fsockopen – Stack Overflow

Intro

This is a working example employing as many of the best-practices, tips, and tricks for using fsockopen on remote streams that I could find.

// max time for script execution
!defined('AA_MAX_TIME') && define('AA_MAX_TIME', 60);// max time for socket reads
!defined('AA_RECV_TIME') && define('AA_RECV_TIME', 30);// max time for socket connect
!defined('AA_CONN_TIME') && define('AA_CONN_TIME', 5);// linebreak
!defined('AA_LF') && define('AA_LF', chr(13).chr(10));// ignore TCP RST i.e. browser stop button
@ignore_user_abort(1);// set the script execution time
@set_time_limit(AA_MAX_TIME);// set the default socket timeout value
@ini_set("default_socket_timeout",AA_RECV_TIME);// output implicitly
@ob_implicit_flush(1);// for binary freads
@set_magic_quotes_runtime();// keep track of script execution time
$aa_time=time();// download each of these urls using fsockopen
aa_dl('http://httpd.apache.org');
aa_dl('http://www.w3.org');
aa_dl('http://www.google.com');
aa_dl('http://www.freebsd.org/cgi/man.cgi?query=connect&sektion=2&apropos=0&manpath=FreeBSD 7.0-RELEASE');
aa_dl('https://www.askapache.com/htaccess/');
aa_dl('http://www.php.net');
aa_dl('http://en.wikipedia.org/wiki/Main_Page');/* returns a socket pointer if valid or displays an error message
sets stream timeout, starts the clock to check for socket read time */
function askapache_get_sock($target,$port){
global
$aa_time_start;
$aa_time_start=time();
if(
false===($fp = @fsockopen($target,$port,$errno,$errstr,AA_CONN_TIME))||!is_resource($fp))
return
askapache_sock_strerror($errno,$errstr);
@
stream_set_timeout($fp, AA_RECV_TIME);
return
$fp;
}
/* writes request, then reads response until EOF, script max, or socket max
returns response on success. Uses buffer to allow size>100megs */
function askapache_txrx($fp,$request,$chunk=1024){
$rec=$buf='';
if(!@
fwrite($fp, $request, strlen($request)))die('fwrite error');
while ( !@
feof($fp) && askapache_time_ok(askapache_time_passed())){
$buf = @fread($fp, $chunk);
$rec .= $buf;
}
if(!@
fclose($fp))die('fclose error');
return
$rec;
}
/* initiates the socket and download for the passed url.
automatically handles gzip, chunked, both, and plain downloads.
uses the long2ip/ip2long for ip validation, uses gethostbyname to
get the ipv4 address which saves fsockopen from having to do the lookup
final data is saved to $rbody but currently only displays headers.*/
function aa_dl($url=NULL){
global
$aa_time;
$ub = @parse_url($url);
if(!isset(
$ub['host'])||empty($ub['host'])) die("bad url $url");
$proto = ($ub['scheme']=='https')?'ssl://':'';
$port = (isset($ub['port'])&&!empty($ub['port'])) ? $ub['port']:(($proto!='')?443:80);
$path = (isset($ub['path'])&&!empty($ub['path'])) ? $ub['path']:'/';
$query = (isset($ub['query'])&&!empty($ub['query'])) ? '?'.$ub['query'] : '';
$host = $ub['host'];
$ipp = @gethostbyname($host);
$ip = ($ipp!=$host) ? long2ip(ip2long($ipp)) : $host;$headers=array(
"GET {$path}{$query} HTTP/1.1",
"Host: {$host}",
'User-Agent: Mozilla/5.0 (AskApache/; https://www.askapache.com/)',
'Accept: text/xml,application/xml,application/xhtml xml,text/html;q=0.9,*/*;q=0.5',
'Accept-Language: en-us,en;q=0.5',
'Accept-Encoding: gzip,deflate',
'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Connection: close','Referer: https://www.askapache.com'
);
$request=join(AA_LF,$headers).AA_LF.AA_LF;$fp=askapache_get_sock($proto.$ip, $port);
if(
$fp){
$rbody=$rec='';$resp_headers=array();
$rec=askapache_txrx($fp,$request);
list(
$resp_headers, $rbody) = explode(AA_LF.AA_LF, trim($rec), 2);
echo
"n<p>$request</p>n<p>$resp_headers</p>n";
$gzip2=(stripos($resp_headers,'Content-Encoding')!==false &&
stripos($resp_headers,'gzip')!==false)?1:;
$chunk=(stripos($resp_headers,'Transfer-Encoding')!==false &&
stripos($resp_headers,'chunked')!==false)?1:;
$rbody=aa_decode_body($rbody,$chunk,$gzip2);
unset(
$rbody);
}
}
/* based on http://us.php.net/manual/en/function.fsockopen.php#75175
ungzips and/or re-assembles transfer-encoded:chunked responses
returns the good response on success */
function aa_decode_body ($str, $chunked, $gzipped){
if(
$gzipped && !$chunked) return aa_gzdecode($str);
if(!
$gzipped && !$chunked) return $str;
$tmp = $str; $str = '';
do {
$tmp = ltrim($tmp);
$pos = strpos($tmp,AA_LF);
$len = hexdec(substr($tmp, , $pos));
if(
$gzipped) $str .= gzinflate(substr($tmp,($pos 12),$len));
else
$str .=substr($tmp,($pos 2),$len);
$tmp = substr($tmp,($len $pos 2));
$chk=trim($tmp);
} while (!empty(
$chk));
return
$str;
}
/* based on http://us2.php.net/manual/en/function.gzencode.php#82520
saves the gzipped data to a tempfile, then outputs the decoded
data to the output buffer using readgzfile, returning the decoded
buffer and deleting the tempfile on success */
function aa_gzdecode($data){
$g=tempnam('/tmp','ff');
@
file_put_contents($g,$data);
ob_start(); readgzfile($g); $d=ob_get_clean(); @unlink($g);
return
$d;
}
/* very cool! this is run during socket reads and checks whether the script
execution time limit or the socket read time limit has been met, killing
the script if so, otherwise returns true. Run with a cron-like process */
function askapache_time_ok($sock_time=) {
global
$aa_time;
if (
time()-$aa_time>AA_MAX_TIME)
die(
'killed script.. time exceeded '.AA_MAX_TIME.' Total: '.$total);
if (
$sock_time>AA_RECV_TIME)
die(
'Killed socket.. time exceeded '.AA_RECV_TIME.' Total: '.$sock_time);
return
true;
}
/* input for askapache_time_ok to keep track of each socket read time time. */
function askapache_time_passed() {
global
$aa_time_start;
return (
time() - $aa_time_start);
}
/* handles fsockopen errors, printing them out though you may want to die on err */
function askapache_sock_strerror($errno,$errstr){
switch(
$errno){
case -
3: $err="Socket creation failed"; break;
case -
4: $err="DNS lookup failure"; break;
case -
5: $err="Connection refused or timed out"; break;
case
104: $err="Connection reset by client"; break;
case
110: $err="Connection timed out"; break;
case
111: $err="Connection refused"; break;
case
113: $err="No route to host"; break;
default:
$err="Connection failed"; break;
}
echo
'<p>Fsockopen failed!'."n[".$errno."] ".$err." (".$errstr.")</p>";
return
false;
}

Php : function reference : network functions : fsockopen php examples tutorials references

sockets - PHP Post data with Fsockopen - Stack Overflow PHP : Function Reference : Network Functions : fsockopen










dante


You may be able to speed this function up by using an IP address instead of a domain. PHP uses getHostByAddr internally in this function anyway, so you can save a step in the function process.

yourpicture


When your connection times out the server may issue Fatal error: Maximum execution time of 30 seconds exceeded in ...
To get around this try this method used with error handling and copied method for ping operation.
<?php
function Ping(){
// false proxy used to generate connection error
$ProxyServer = "116.155.95.163";
$ProxyPort = 8080;
$timeout=10;
echo "Opening ProxyServer $ProxyServer
";
// must use next two statements
Set_Time_Limit(0);  //Time for script to run .. not sure how it works with 0 but you need it
Ignore_User_Abort(True); //this will force the script running at the end

$handle = fsockopen($ProxyServer, $ProxyPort,$errno,$errstr,$timeout);
if (!$handle){
echo "Failed to open ProxyServer $ProxyServer errno=$errno,errstr=$errstr
";
return 0;
}
else {
// copied method for PING like time operation
$status = socket_get_status($handle);
echo "Opened ProxyServer $ProxyServer
";

//Time the responce
list($usec, $sec) = explode(" ", microtime(true));
$start=(float)$usec (float)$sec;

$timeout=120;
stream_set_timeout($handle,$timeout);      
//send somthing
ini_set('display_errors','0');
$write=fwrite($handle,"echo thisn");
if(!$write){
return 0;
}

echo "Try To Read
";
stream_set_blocking($handle,0);  
//Try to read. the server will most likely respond with a "ICMP Destination Unreachable" and end the read. But that is a responce!
fread($handle,1024);
fclose($handle);
echo "Read
";
ini_set('display_errors','1');
//Work out if we got a responce and time it          
list($usec, $sec) = explode(" ", microtime(true));
$laptime=((float)$usec (float)$sec)-$start;
if($laptime>$timeout)
return 0;
//else  
// $laptime = round($laptime,3);
return $laptime;
}
}
// must use ErrorHandler to avoid php error being printed to screen
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
// you can set this to what ever you like.
echo "In Error Handler
";
return 0;
}
$old_error_handler = set_error_handler("userErrorHandler");
$time = Ping();
echo "Time=$time
";
echo "Done Checking
";
?>
Response Will be:
Opening ProxyServer 116.155.95.163
In Error Handler
Failed to open ProxyServer 116.155.95.163 errno=10060,errstr=A connection attempt failed
because the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond.
Time=0
Done Checking
Thanks to everyone for your source code examples.
AndE

sysco/al – developer


We have implemented a Syslog class in PHP following the RFC 3164 rules. Using this class, it is possible to send syslog messages to external servers.
We use this class for example to log information, to synchronize some processes or to launch external "threads".
Class abstract, full class implementation can be found at http://developer.sysco.ch/php/
<?php
// (...)
class Syslog
{
var $_facility; // 0-23
var $_severity; // 0-7
var $_hostname; // no embedded space, no domain name, only a-z A-Z 0-9 and other authorized characters
var $_fqdn;
var $_ip_from;
var $_process;
var $_content;
var $_msg;
var $_server;   // Syslog destination server
var $_port;     // Standard syslog port is 514
var $_timeout;  // Timeout of the UDP connection (in seconds)
// (...)
function Send($server = "", $content = "", $timeout = 0)
{
// (...)
$actualtime = time();
$month      = date("M", $actualtime);
$day        = substr("  ".date("j", $actualtime), -2);
$hhmmss     = date("H:i:s", $actualtime);
$timestamp  = $month." ".$day." ".$hhmmss;
$pri    = "<".($this->_facility*8 $this->_severity).">";
$header = $timestamp." ".$this->_hostname;
// (...)
$msg = $this->_process.": ".$this->_fqdn." ".$this->_ip_from." ".$this->_content;
$message = substr($pri.$header." ".$msg, 0, 1024);
$fp = fsockopen("udp://".$this->_server, $this->_port, $errno, $errstr, $this->_timeout);
if ($fp)
{
fwrite($fp, $message);
fclose($fp);
$result = $message;
}
else
{
$result = "ERROR: $errno - $errstr";
}
return $result;
}
// (...)
?>
Example
<?php
require_once('syslog.php');
$syslog = new Syslog();
$syslog->Send('192.168.0.12', 'My first PHP syslog message');
?>

terminal


Try this.
Use AUTH when necessary.
Read RFC 821 when having problems.
<?php
$handle = smtp_connect($smtp_server, 25, 30, 1, 1, 1);
echo smtp_command($handle, "EHLO $domainrn", 1, 1);
echo smtp_command($handle, "MAIL FROM:<$from_mail>rn", 1, 1);
echo smtp_command($handle, "RCPT TO:<$to_mail>rn", 1, 1);
echo smtp_command($handle, "DATArn", 1, 1);
echo smtp_command($handle, "$messagern.rn", 1, 1);
// don't do it like this - it will hang up
// echo smtp_command($handle, "$message", 1, 1);
// echo smtp_command($handle, "rn.rn", 1, 1);
echo smtp_command($handle, "QUITrn", 1, 1);
smtp_close($handle);
function smtp_connect($host, $port, $timeout=30, $echo_command=False, $echo_response=False, $nl2br=False)
{
$errno = 0;
$errstr = 0;
if($echo_command)
{
if($nl2br) { echo nl2br("CONNECTING TO $hostrn"); }
else { echo "CONNECTING TO $hostrn"; }
}
$handle = fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$handle)
{
if($echo_command)
{
if($nl2br) { echo nl2br("CONNECTION FAILEDrn"); }
else { echo "CONNECTION FAILEDrn"; }
}
return False;
}
if($echo_command)
{
if($nl2br) { echo nl2br("SUCCESSrn"); }
else { echo "SUCCESSrn"; }
}
$response = fgets($handle,1);
$bytes_left = socket_get_status($handle);
if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
if($echo_response)
{
if($nl2br) { echo nl2br($response); }
else { echo $response; }
}
return $handle;
}
function smtp_command($handle, $command, $echo_command=False, $nl2br=False)
{
if($echo_command)
{
if($nl2br) { echo nl2br($command); }
else { echo $command; }
}
fputs($handle, $command);
$response = fgets($handle,1);
$bytes_left = socket_get_status($handle);
if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
if($nl2br) { return nl2br($response); }
else { return $response; }
}

function smtp_close($handle)
{
fclose($handle);
}
?>

xbensemhoun


To make a telnet connection with a Cisco router:
$cfgServer = "192.168.0.10";  //IP of your router
$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;
$usenet = fsockopen($cfgServer, $cfgPort, &$errno, &$errstr, $cfgTimeOut);
if(!$usenet)
{
echo "Connexion failedn";
exit();
}
else
{
echo "Connectedn
";
fputs ($usenet, "totorn");
fputs ($usenet, "enrn");
fputs ($usenet, "tuturn");
fputs ($usenet, "exitrn");
while (!feof($usenet))
{
echo ". ".fgets($usenet, 128)."
n";
}
}
Then you will have:
Connected
. ÿû

pulstar


alexander wegener


brage a t jeffnappi d.o.t commie


thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.
// function connects to an array of URLS at the same time
// and returns an array of results.
function multiHTTP ($urlArr) {
$sockets = Array(); // socket array!
$urlInfo = Array(); // info arr
$retDone = Array();
$retData = Array();
$errno   = Array();
$errstr  = Array();
for ($x=0;$x<count($urlArr);$x ) {
$urlInfo[$x] = parse_url($urlArr[$x]);
$urlInfo[$x][port] = ($urlInfo[$x][port]) ? $urlInfo[$x][port] : 80;
$urlInfo[$x][path] = ($urlInfo[$x][path]) ? $urlInfo[$x][path] : "/";
$sockets[$x] = fsockopen($urlInfo[$x][host], $urlInfo[$x][port],
$errno[$x], $errstr[$x], 30);
socket_set_blocking($sockets[$x],FALSE);
$query = ($urlInfo[$x][query]) ? "?" . $urlInfo[$x][query] : "";
fputs($sockets[$x],"GET " . $urlInfo[$x][path] . "$query HTTP/1.0rnHost: " .
$urlInfo[$x][host] . "rnrn");
}
// ok read the data from each one
$done = false;
while (!$done) {
for ($x=0; $x < count($urlArr);$x ) {
if (!feof($sockets[$x])) {
if ($retData[$x]) {
$retData[$x] .= fgets($sockets[$x],128);
} else {
$retData[$x] = fgets($sockets[$x],128);
}
} else {
$retDone[$x] = 1;
}
}
$done = (array_sum($retDone) == count($urlArr));
}
return $retData;
}
# also if anyone has idea to improve this that would be wonderful

Похожее:  ЗАГС Серпухов: адреса, режим работы, телефоны, сайт

sivann


This is an ident request example. If your client is running identd your real username will be known by the server.
It is also usefull to identify people bypassing IP ACLs by using SOCKS proxy and dynamic IP forwarding. If the socks proxy server uses ident (most unices do) you will know his real username.
For more information see RFC1413
Timeout of 2 seconds in the example may not be enough.
<?
error_reporting(E_ALL);
$remip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
$remport = $HTTP_SERVER_VARS['REMOTE_PORT'];
ob_implicit_flush();
$fp = fsockopen($remip, 113, $errno, $errstr, 2);
if (!$fp) {
echo "$errstr ($errno)
n";
exit;
}
else {
$out = "$remport, 80rn";
fwrite($fp, $out);
$answer=fgets($fp, 128);
}
fclose($fp);
$ansparts=explode(":",$answer);
$user=chop($ansparts[3]);
echo "You are $user@$remip:$remport";
?>

asalamanca


This is a very fast program for test a form or link (many times).
<?php
$repeat  = 100;  // How many times repeat the test
$timeout = 100;  // Max time for stablish the conection
$size    = 16;   // Bytes will be read (and display). 0 for read all
$server  = '64.246.30.37';            // IP address
$host    = 'www.foo.com';             // Domain name
$target  = '/poll/answer.asp';        // Specific program
$referer = 'http://www.test.com/';    // Referer
$port    = 80;
// Setup an array of fields to get with then create the get string
$gets = array ( 'get_field_1' => 'somevalue',
'get_field_2' => 'somevalue' );
// Setup an array of fields to post with then create the post string
$posts = array ( 'post_field_1' => 'somevalue',
'post_field_2' => 'somevalue' );
// That's all. Now the program proccess $repeat times
$method = "GET";
if ( is_array( $gets ) ) {
$getValues = '?';
foreach( $gets AS $name => $value ){
$getValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
}
$getValues = substr( $getValues, 0, -1 );
} else {
$getValues = '';
}
if ( is_array( $posts ) ) {
foreach( $posts AS $name => $value ){
$postValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
}
$postValues = substr( $postValues, 0, -1 );
$method = "POST";
} else {
$postValues = '';
}
$request  = "$method $target$getValues HTTP/1.1rn";
$request .= "Host: $hostrn";
$request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
$request .= "Gecko/20021204rn";
$request .= 'Accept: text/xml,application/xml,application/xhtml xml,';
$request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1rn";
$request .= "Accept-Language: en-us, en;q=0.50rn";
$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9rn";
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66rn";
$request .= "Keep-Alive: 300rn";
$request .= "Connection: keep-alivern";
$request .= "Referer: $refererrn";
$request .= "Cache-Control: max-age=0rn";
if ( $method == "POST" ) {
$lenght = strlen( $postValues );
$request .= "Content-Type: application/x-www-form-urlencodedrn";
$request .= "Content-Length: $lenghtrn";
$request .= "rn";
$request .= $postValues;
}
for ( $i = 0; $i < $repeat; $i ) {
$socket  = fsockopen( $server, $port, $errno, $errstr, $timeout );
fputs( $socket, $request );
if ( $size > 0 ) {
$ret = fgets( $socket, $size );
} else {
$ret = '';
while ( !feof( $socket ) ) {
$ret .= fgets( $socket, 4096 );
}
}
fclose( $socket );
echo "<hr> $i -- $content $ret";
}
?>
Alejandro Salamanca
RedCetus.com

yadiutama_skom


jeremy


The only think wrong with richard burton's code as regarding apache is that
$byte != "\r" should be
$byte == "r"

michiel


The following snippet allows you to retrieve the title oa page.
Great for rewriting auto-url detectors to display the actual title rather then http://...
<?
echo get_url_title("http://www.php.net/cal.php?id=409");
function get_url_title($url, $timeout = 2)
{
$url = parse_url($url);
if(!in_array($url['scheme'],array('','http')))
return;
$fp = fsockopen ($url['host'], ($url['port'] > 0 ? $url['port'] : 80), $errno, $errstr, $timeout);
if (!$fp)
{
return;
// echo "$errstr ($errno)
n";
}
else
{
fputs ($fp, "GET /".$url['path'].($url['query'] ? '?'.$url['query'] : '')." HTTP/1.0rnHost: ".$url['host']."rnrn");
$d = '';
while (!feof($fp))
{
$d .= fgets ($fp,2048);
if(preg_match('~(</head>|<body>|(<title>s*(.*?)s*</title>))~i', $d, $m))
break;
}
fclose ($fp);
return $m[3];
}
}
?>

ahauk


The following script will login to a POP3 account using the username, password and server name provided via a standard form; determine the amount of messages using a binary search; then purge all messages.
<?php
$server = $_POST["server"];
$user = $_POST["user"];
$pass = $_POST["pass"];
$count = 1;
$low = 0;
$mid = 0;
$high = 100000;
$connection = fsockopen($server, 110, $errno, $errstr, 30);
if(!$connection) {
print "Connect Failed: $errstr ($errno)";
} else {
$output = fgets($connection, 128);
fputs($connection, "user $usern");
$output = fgets($connection, 128);
fputs($connection, "pass $passn");
$output = fgets($connection, 128);
while($low < $high - 1) {
$mid = floor(($low $high) / 2);
fputs($connection, "list $midn");
$output = fgets($connection, 128);
$subout = substr($output, 0, 4);
if($subout == " OK ") {
$low = $mid;
continue;
}
elseif($subout == "-ERR") {
$high = $mid;
continue;
} else {
break;
print "An error has occurred. Please try again.";
}
}
$limit = $mid - 1;
while($count <= $limit) {
fputs($connection, "dele $countn");
fgets($connection, 128);
$count = $count 1;
}
fputs($connection, "quitn");
}
fclose($connection);
print "Successfully removed $limit messages.";
?>

v13 phpnet


The following function performs pop3 authentication. Returns NULL on error, or true/false to indicate username/password matching:
$address is the hostname of the server and $ssl is a boolean that indicates whether an SSL connection is requested.
<?php
function pop3authCheck($username, $password, $address, $ssl)
{
if ($ssl)
$uri="ssl://$address:995";
else
$uri="tcp://$address:110";
$fp=fsockopen($uri);
if (!$fp)
return(NULL);
$st=fgets($fp, 512);
if (substr($st, 0, 3)!=" OK")
{
fclose($fp);
return(NULL);
}
$st="USER $usernamen";
if (fwrite($fp, $st)!=strlen($st))
{
fclose($fp);
return(NULL);
}
$st=fgets($fp, 512);
if (substr($st, 0, 3)!=" OK")
{
fclose($fp);
return(NULL);
}
$st="PASS $passwordn";
if (fwrite($fp, $st)!=strlen($st))
{
fclose($fp);
return(NULL);
}
$st=fgets($fp, 512);
fclose($fp);
if (substr($st, 0, 3)==" OK")
return(true);
else if (substr($st, 0, 4)==" ERR")
return(false);
else
return(NULL);
}
?>

konrad dot meyer


The documentation example is of a GET request. I have found POST documentation to be lacking, and here's a function to easily simulate submitting form data:
<?php
# $host includes host and path and filename
# ex: "myserver.com/this/is/path/to/file.php"
# $query is the POST query data
# ex: "a=thisstring&number=46&string=thatstring
# $others is any extra headers you want to send
# ex: "Accept-Encoding: compress, gziprn"
function post($host,$query,$others=''){
$path=explode('/',$host);
$host=$path[0];
unset($path[0]);
$path='/'.(implode('/',$path));
$post="POST $path HTTP/1.1rnHost: $hostrnContent-type: application/x-www-form-urlencodedrn${others}User-Agent: Mozilla 4.0rnContent-length: ".strlen($query)."rnConnection: closernrn$query";
$h=fsockopen($host,80);
fwrite($h,$post);
for($a=0,$r='';!$a;){
$b=fread($h,8192);
$r.=$b;
$a=(($b=='')?1:0);
}
fclose($h);
return $r;
}
?>

ryan1_00


Sorry for multiple submission of this but Added @ to suppress errors and a few exmples:
Also note that this script checks specific ports so you need to have the correct port open on the server for this to work.
E.g if i have a windows domain controller and it is servering LDAP then the following would be used to check it is online:
chkServer("MyDC", "389");
for a webserver
chkServer("MyWebSvr", "80");
etc etc
--------------------------------------------------------
// check if a server is up by connecting to a port
function chkServer($host, $port)
{  
$hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure
if ($hostip == $host) // if the IP is not resloved
{
echo "Server is down or does not exist";
}
else
{
if (!$x = @fsockopen($hostip, $port, $errno, $errstr, 5)) // attempt to connect
{
echo "Server is down";
}
else
{
echo "Server is up";
if ($x)
{
@fclose($x); //close connection (i dont know if this is needed or not).
}
}  
}
}

dna


Something useful for ICQ:
<?php
$icquin = "197829943";
function GetICQ($uin) {
if (!is_numeric($uin)) return FALSE;
$fp = fsockopen('status.icq.com', 80, &$errno, &$errstr, 8);
if (!$fp) {
return "N/A";
}
else {
$request = "HEAD /online.gif?icq=$uin HTTP/1.0rn"
."Host: web.icq.comrn"
."Connection: closernrn";
fputs($fp, $request);
do {
$response = fgets($fp, 1024);
}
while (!feof($fp) && !stristr($response, 'Location'));
fclose($fp);
if (strstr($response, 'online1')) return 'Online';
if (strstr($response, 'online0')) return 'Offline';
if (strstr($response, 'online2')) return 'N/A';
// N/A means, this User set the Option, his Online
// Status cannot be shown over the Internet
return FALSE;
}
}
echo GetICQ($icquin);
?>

alex


Setting up SSL connection to server that requires client certificate (https).
Function fsockopen() has 5 arguments only in PHP5. There is sixth undocumented argument in PHP4 fsockopen() function . Therefore code in note 'alex at renesource dot lv 16-Mar-2004 09:07' will work with PHP4 only.
You can use the following code to post request to HTTPS server that requires client certificate to establish SSL connection:
<?php
# working vars
$host = 'ssl.host.com';
$service_uri = '/some/service/address';
$local_cert_path = '/path/to/keys.pem';
$local_cert_passphrase = 'pass_to_access_keys';
$request_data = '<some><xml>data</xml></some>';
# array with the options to create stream context
$opts = Array();
# compose HTTP request header
$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: text/xml\r\n";
$header .= "Content-Length: ".strlen($request_data)."\r\n";
$header .= "Connection: close";
# define context options for HTTP request (use 'http' index, NOT 'httpS')
$opts['http']['method'] = 'POST';
$opts['http']['header'] = $header;
$opts['http']['content'] = $request_data;
# define context options for SSL transport
$opts['ssl']['local_cert'] = $local_cert_path;
$opts['ssl']['passphrase'] = $local_cert_passphrase;
# create stream context
$context = stream_context_create($opts);
# POST request and get response
$filename = 'https://'.$host.$service_uri;
$content = file($filename, false, $context);
$response_data = implode('', $content);
?>

simon riget


Ping from PHP script. (Without system call)
This is of cause not a real ping since there is no support for ICMP. So it can't send a packet and get it back. But the important thing is to get a response from the server, even if it is only a ICMP  error message. That way it verifies the servers existens and calculate the round trip time, which is the essential function of ping. It work well on all servers I have tried, with the echo service running.
<?
$host='www.php.com';
$timeout=2;

//Open the socket
$handle=fsockopen('ddp://'.$host, 7, $errno, $errstr, $timeout);
if (!$handle)
echo "$errstr ($errno)
rn";
else {
//Set read timeout
stream_set_timeout($handle, $timeout);
for($i=0;$i<3;$i ){
//Time the responce
list($usec, $sec) = explode(" ", microtime(true));
$start=(float)$usec (float)$sec;

//send somthing
$write=fwrite($handle,"echo thisn");
if(!$write){
echo "Error in writing to socked
rn";
break;
}
echo 'Send packet to '.$host;

//Try to read. the server will most likely respond with a "ICMP Destination Unreachable" and end the read. But that is a responce!
fread($handle,1024);

//Work out if we got a responce and time it
list($usec, $sec) = explode(" ", microtime(true));
$laptime=((float)$usec (float)$sec)-$start;
if($laptime>$timeout)
echo " : No reply
rn";
else
echo " : Round trip = ".round($laptime,3)." s
rn";
}
fclose($handle);
}
?>

bjorn


Modified code for telnet to work with not-so-fast connections.
The old version garbles the output and/or cuts the output before
it is finished when output is above about 100 lines.
<?php
# This is the difficult part, the Telnet header
$header1=chr(0xFF).chr(0xFB).chr(0x1F).chr(0xFF).chr(0xFB).
chr(0x20).chr(0xFF).chr(0xFB).chr(0x18).chr(0xFF).chr(0xFB).
chr(0x27).chr(0xFF).chr(0xFD).chr(0x01).chr(0xFF).chr(0xFB).
chr(0x03).chr(0xFF).chr(0xFD).chr(0x03).chr(0xFF).chr(0xFC).
chr(0x23).chr(0xFF).chr(0xFC).chr(0x24).chr(0xFF).chr(0xFA).
chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18).chr(0xFF).
chr(0xF0).chr(0xFF).chr(0xFA).chr(0x20).chr(0x00).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0x2C).chr(0x33).
chr(0x38).chr(0x34).chr(0x30).chr(0x30).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x27).chr(0x00).chr(0xFF).chr(0xF0).
chr(0xFF).chr(0xFA).chr(0x18).chr(0x00).chr(0x58).chr(0x54).
chr(0x45).chr(0x52).chr(0x4D).chr(0xFF).chr(0xF0);
$header2=chr(0xFF).chr(0xFC).chr(0x01).chr(0xFF).chr(0xFC).
chr(0x22).chr(0xFF).chr(0xFE).chr(0x05).chr(0xFF).chr(0xFC).chr(0x21);
# connecting
$fp=fsockopen("127.0.0.1",23);
# sending the Telnet header
fputs($fp,$header1);
usleep(125000);
fputs($fp,$header2);
usleep(125000);
# login
fputs($fp,"userr");
usleep(125000);
fputs($fp,"users.passr");
usleep(125000);
# root looks nice
fputs($fp,"sur");
usleep(125000); # takes some time, we had to wait
fputs($fp,"root.passr");
# some tests
fputs($fp,"ifconfigr");        
fputs($fp,"echo year telnet php connect works|wallr");
# we had to wait
usleep(125000);
# show the output
do
{  
$output.=fread($fp, 80); // read line by line, or at least small chunks
$stat=socket_get_status($fp);
}
while($stat["unread_bytes"]);

$output = str_replace("n", "
", $output);
echo $output;
fclose($fp);
?>

duukkis


ittasks


login to the site prior to downloading page:
In some wierd situations site security is based on
ASPSESSION ID and where could be a
login asp  script in one place, and the actual page with
information in another place.
for such cases you have to submit ( POST ) you login and
password first, when grab ASP session (and also some
cookies from response, and when use that ASP SESSION in
second request to the actual page: (i took some parts of
codes from other ppl)
<?php
//submit login form: (url, post data, extra headers (optional))
//do not put  http into URL, just domain name
$mycookies = GetCookies("www.yourdomain.com/login.login.asp",
"password=12345&username=your_username&submit=LOGIN&set=Y","");
//some extra params if you need them
// echo "Cookies:
<pre>n".$mycookies."n</pre>";
//$body =PostPage("www.yourdomain.com/coolpage.asp",
//"action=zzz",$mycookies);
//echo "
Body:
n".$body."n";
//im using get page - so it goes like this:
$opts = array('http'=>array('method'=>"GET",
'header'=>"Accept-language: enrnCookie: ".$mycookies."rn" ));
$context = stream_context_create($opts);
$fp = fopen('http://www.yourdomain.com/coolpage.asp?p1=1&p2=23', 'r', false, $context);
fpassthru($fp);
$html = fread($fp, 1000000);
fclose($fp);
echo $html;
function PostPage($host,$query,$others=''){
$path=explode('/',$host);
$host=$path[0];
unset($path[0]);
$path='/'.(implode('/',$path));
$post="POST $path HTTP/1.1rnHost: $hostrn";
$post.="Content-type: application/x-www-form-";
$post.="urlencodedrn${others}";
$post.="User-Agent: Mozilla 4.0rnContent-length: ";
$post.=strlen($query)."rnConnection: closernrn$query";
$h=fsockopen($host,80);
fwrite($h,$post);
for($a=0,$r='';!$a;){
$b=fread($h,8192);
$r.=$b;
$a=(($b=='')?1:0);
}
fclose($h);
return $r;
}
function GetCookies($host,$query,$others=''){
$path=explode('/',$host);
$host=$path[0];
unset($path[0]);
$crlf = "rn";
$path='/'.(implode('/',$path));
$post="POST $path HTTP/1.1rnHost: $hostrn";
$post.="Content-type: application/x-www-form-urlencodedrn${others}";
$post.="User-Agent: Mozilla 4.0rnContent-length: ";
$post.=strlen($query)."rnConnection: closernrn$query";
$h=fsockopen($host,80);
fwrite($h,$post);
$r="";
for($a=0;!$a;){
$b=fread($h,512);
echo $b;
$r.=$b;
$gotSession=strpos($r,"ASPSESSION");
if($gotSession)
if(strpos($r, $crlf . $crlf,$gotSession)>0) break;
$a=(($b=='')?1:0);
}
fclose($h);
$arr = split("Set-Cookie:",$r);
$AllCookies="";$count=1;
while ($count < count($arr)) {
$AllCookies.=substr($arr[$count].";",
0,strpos($arr[$count].";",";") 1);
$count ;}
return $AllCookies;
}
?>
It's not optimized , but i hope someone might find it usefull.
Best Regards
DRY_GIN

joe

Похожее:  RADIUS | Все про протокол RADIUS Accounting ExpertBilling

just a quick note for users attempting https and thinking they must resort to curl or alternate methods -
you can use fsockopen, just read the docs closely.  basically they are saying to use 'ssl://' for a HTTPS (SSL) web request.
so this would work for authorize.net, and others; even for that paypal IPN - however I think it would be best to leave the site and deal with paypal's form:
$host = "somehost.somedomain.com";
$port = 443;
$path = "/the/url/path/file.php"; //or .dll, etc. for authnet, etc.
//you will need to setup an array of fields to post with
//then create the post string
$formdata = array ( "x_field" => "somevalue");
//build the post string
foreach($formdata AS $key => $val){
$poststring .= urlencode($key) . "=" . urlencode($val) . "&";
}
// strip off trailing ampersand
$poststring = substr($poststring, 0, -1);
$fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 30);
if(!$fp){
//error tell us
echo "$errstr ($errno)n";
}else{
//send the server request
fputs($fp, "POST $path HTTP/1.1rn");
fputs($fp, "Host: $hostrn");
fputs($fp, "Content-type: application/x-www-form-urlencodedrn");
fputs($fp, "Content-length: ".strlen($poststring)."rn");
fputs($fp, "Connection: closernrn");
fputs($fp, $poststring . "rnrn");
//loop through the response from the server
while(!feof($fp)) {
echo fgets($fp, 4096);
}
//close fp - we are done with it
fclose($fp);
}

rob


Just a note to everyone who is using fsockopen and fread / fgets for a HTTP connection.
Unless you specify "Connection: Close" in your headers you will need to wait for the socket to time out before feof($streamPointer) to return true.
This has wasted 2 days of my time, grr!
-Rob

martjean77


Just a correction
The function decode_jbr at ya-right dot com work nice for me (thanks), but is missing a last case, for when the response is not chunked (because it's too short for exemple), here a corrected function :
function decode_body ( $info, $str, $eol = "rn" )
{
$tmp = $str;
$add = strlen ( $eol );
$str = '';
if ( isset ( $info['transfer-encoding'] ) && $info['transfer-encoding'] == 'chunked' )
{
do
{
$tmp = ltrim ( $tmp );
$pos = strpos ( $tmp, $eol );
$len = hexdec ( substr ( $tmp, 0, $pos ) );
if ( isset ( $info['content-encoding'] ) )
{
$str .= gzinflate ( substr ( $tmp, ( $pos $add 10 ), $len ) );
}
else
{
$str .= substr ( $tmp, ( $pos $add ), $len );
}
$tmp = substr ( $tmp, ( $len $pos $add ) );
$check = trim ( $tmp );
}
while ( ! empty ( $check ) );
}
else if ( isset ( $info['content-encoding'] ) )
{
$str = gzinflate ( substr ( $tmp, 10 ) );
}
else {
$str = $tmp;
}
return $str;
}

johnyu


It appears with PHP 4.3.2, on windows machines. fsockopen isn't able to use the ssl:// prefix even if you have the OpenSSL dll loaded in php.ini
On the otherhand, with PHP 4.5 CVS, it looks like SSL support for fsockopen is already compiled in... but it's missing the zip lib which I also need =(

richardaburton


Improved HTTP/1.1 chunked transfer-encoding example.
The sample code given below by Jack does not function correctly when run against a recent version of Apache (I'm assuming that this did once work, but from the HTTP/1.1 spec I can only assume if it did work it was based mostly on luck).
<?php
$header = "";
$response = "";
// connect
if (!($request=fsockopen('whatever.com',80,$errno,$errstr))) exit($errstr);
else {
socket_set_timeout($request,10);
// send request
fwrite($request,$post);
// get header
do $header.=fread($request,1); while (!preg_match('/\r\n\r\n$/',$header));
// check for chunked encoding
if (preg_match('/Transfer\-Encoding:\s chunked\r\n/',$header))
do {
$byte = "";
$chunk_size="";
do {
$chunk_size.=$byte;
$byte=fread($request,1);
} while ($byte!="\r");      // till we match the CR
fread($request, 1);         // also drop off the LF
$chunk_size=hexdec($chunk_size); // convert to real number
$response.=fread($request,$chunk_size);
fread($request,2);          // ditch the CRLF that trails the chunk
} while ($chunk_size);         // till we reach the 0 length chunk (end marker)
else {
// check for specified content length
if (preg_match('/Content\-Length:\s ([0-9]*)\r\n/',$header,$matches)) {
$response=fread($request,$matches[1]);
} else {
// not a nice way to do it (may also result in extra CRLF which trails the real content???)
while (!feof($request)) $response .= fread($request, 4096);
}
}
// close connection
fclose($request);
}
// do something useful with the response
print($header);
print($response);
?>
Richard.

dante


If you're using code like the manual's example, it is a good idea to keep using HTTP/1.0 instead of changing it to HTTP/1.1. Using HTTP/1.1 with fsockopen sometimes results in junk before and after the body content (but not in the headers).

dmitry dot polushkin


If you want to GET/POST some page through the HTTP protocol and if you want to keep-alive your connection, you may have a problem with a loop-stuck. Here is hint how to solve it:
<?php
$fp = fsockopen ("www.php.net", 80, $errno, $errstr, 30);
if(!$fp) {
echo $errstr;
} else {
fwrite($fp, "GET / HTTP/1.1rnHost: www.php.netrnConnection: Keep-Alivernrn");
$data = '';
while(!feof($fp)) {
$data .= fread($fp, 4096);
if(substr($data, -9)=="rnrn0rnrn") {
exit;
}
}
}
echo $data;
?>

sergiopaternoster


If you want to connect via Telnet, it could be useful to set also the Terminal Type (some OS requires it)
$IAC  = chr(255);   /* interpret as command: */
$SB = chr(250);     /* interpret as subnegotiation */
$SE = chr(240);     /* end sub negotiation */
$TELOPT_TTYPE = chr(24);     /* terminal type */
$TELQUAL_IS = chr(0); /* Option is... */
//sending Terminal Type
fwrite($sock,$IAC.$SB.$TELOPT_TTYPE.$TELQUAL_IS.'vt100'.$IAC.$SE);
ciao
Sergio Paternoster

na8ur


if you send some header information to any server eg. sending cookie data, don't forget to have rnrn (double new line) at the end of your header data.

saul dot dobney


If you are using fsockopen to access webpage, but come across a redirect (Location: ) in the header and want to find and follow the redirect as in this snippet:
while (!feof($fp)) {
$line=fgets($fp, 1024);
if (stristr($line,"location:")!="") {
$redirect=preg_replace("/location:/i","",$line);
}
}
Then don't forget to trim($redirect) before trying to follow this new link as $redirect actually has a rn on the end of it and won't give you a valid path in the next iteration otherwise. A six hour bug.
Saul Dobney

tylernt


If you are composing your own HTTP POST to upload to a form or upload a file, you need to realize that when you *use* your boundary to separate the parts, you need to prepend two dashes (--) to whatever you *defined* your boundary as. For example, if you define your boundary as --1234, then you need to send ----1234 as your boundaries.
If you forget to prepend those two dashes, it is particularly frustrating because the server will return a 200 OK / accepted code, but your receiving form will not recieve any POSTed data.
I only wasted a day and a half on that one.

04-dec-2006 04:34


I've had issues with some of the handlers for chunked http 1.1 responses.  Here's a method that worked for me, if it works for you as well, then cheers 😛
<?php
function httpSocketConnection($host, $method, $path, $data)
{
$method = strtoupper($method);

if ($method == "GET")
{
$path.= '?'.$data;
}

$filePointer = fsockopen($host, 80, $errorNumber, $errorString);

if (!$filePointer)
{
logEvent('debug', 'Failed opening http socket connection: '.$errorString.' ('.$errorNumber.')<br/>n');
return false;
}
$requestHeader = $method." ".$path."  HTTP/1.1rn";
$requestHeader.= "Host: ".$host."rn";
$requestHeader.= "User-Agent:   Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0rn";
$requestHeader.= "Content-Type: application/x-www-form-urlencodedrn";
if ($method == "POST")
{
$requestHeader.= "Content-Length: ".strlen($data)."rn";
}

$requestHeader.= "Connection: closernrn";

if ($method == "POST")
{
$requestHeader.= $data;
}
fwrite($filePointer, $requestHeader);

$responseHeader = '';
$responseContent = '';
do
{
$responseHeader.= fread($filePointer, 1);
}
while (!preg_match('/\r\n\r\n$/', $responseHeader));

if (!strstr($responseHeader, "Transfer-Encoding: chunked"))
{
while (!feof($filePointer))
{
$responseContent.= fgets($filePointer, 128);
}
}
else
{
while ($chunk_length = hexdec(fgets($filePointer)))
{
$responseContentChunk = '';

logEventToTextFile('debug', $chunk_length);
$read_length = 0;

while ($read_length < $chunk_length)
{
$responseContentChunk .= fread($filePointer, $chunk_length - $read_length);
$read_length = strlen($responseContentChunk);
}
$responseContent.= $responseContentChunk;

fgets($filePointer);

}

}
logEventToTextFile('debug', $responseContent);

return chop($responseContent);
}
?>

bradland


warezthebeef


I ran into a problem where I needed to make an fsockopen() style connection from one specific ip address on a server with multiple ip aliases. Unfortunately fsockopen() does not allow the specification of a source address making it unsuitable. I could not find any other solutions elsewhere so here is mine for those with php 5.1.0 or greater.
// connect to the internet using the '192.168.0.100' IP
$opts = array('socket' => array('bindto' => '192.168.0.100:0'));
$context = stream_context_create($opts);
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);
Now $fp can be used like a resource handle returned by a vanilla fsockopen() call!

robin


I have found, when using fsockopen() and the POST method, that using HTTP/1.1 is VERY significantly slower than HTTP/1.0 (at least for the server I'm querying, an Orion-based server). Also, using cURL tended to be faster than fsockopen(), though only slightly. For example, here was a recent set of data (for the same exact request in each case):
cURL: 4.2sec
fsockopen() HTTP/1.0: 4.9sec
fsockopen() HTTP/1.1: 19.9sec (!)
I'm not sure why this was occurring. Perhaps it has something to do with the Orion server, which I have little experience with. However, it was not a fluke, and I double-checked the code to make sure there were no errors.
EDITORS NOTE: HTTP/1.1 uses persistent connection causing this delay. Use "Connection: close" header to disable it.

jmpz


I had a similar problem to a previous poster with terrible performance. I tried changing to HTTP 1.0 but that didn't fix it. I then removed the line:
connection: keep-alive
This fixed it. What took 13 seconds now takes 1.

albertohf


I had a problem receving a "Content-Transfer: chunked" response i tried some prior codes but i had some problems too and i decided to code my own (it post something and receive the response although it's chunked). I hope you enjoy...
function doPost($uri,$postdata,$host){
$da = fsockopen($host, 80, $errno, $errstr);
if (!$da) {
echo "$errstr ($errno)<br/>n";
echo $da;
}
else {
$salida ="POST $uri  HTTP/1.1rn";
$salida.="Host: $hostrn";
$salida.="User-Agent: PHP Scriptrn";
$salida.="Content-Type: application/x-www-form-urlencodedrn";
$salida.="Content-Length: ".strlen($postdata)."rn";
$salida.="Connection: closernrn";
$salida.=$postdata;
fwrite($da, $salida);
while (!feof($da))
$response.=fgets($da, 128);
$response=split("rnrn",$response);
$header=$response[0];
$responsecontent=$response[1];
if(!(strpos($header,"Transfer-Encoding: chunked")===false)){
$aux=split("rn",$responsecontent);
for($i=0;$i<count($aux);$i )
if($i==0 || ($i%2==0))
$aux[$i]="";
$responsecontent=implode("",$aux);
}//if
return chop($responsecontent);
}//else
}//function-doPost

anarchy


I don't know why it's not mentioned here (or am I missing something), but the DEFAULT stream timeout is set according to default_socket_timeout in your php.ini file.  Took forever for me to dig that up....

chris


I also needed a file upload via fsockopen and tried to work with Chris Snyders posting above:
========================
POST /path/to/script.php HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: $requestlen
--AaB03x
content-disposition: form-data; name="field1"
$field1
--AaB03x
content-disposition: form-data; name="field2"
$field2
--AaB03x
content-disposition: form-data; name="userfile"; filename="$filename"
Content-Type: $mimetype
Content-Transfer-Encoding: binary
$binarydata
--AaB03x--
==========================
I discovered some weird behaviour on my Linux server with PHP 4.0 and wanted to let you know 🙂
1) Lines needed to end with rn (else the last character of the value was cropped)
2) I needed to remove Content-Type and Content-Transfer-Encoding from the binary "userfile" - else the uploaded file contained these strings and was invalid!
3) The receiving script couldn't reference to the variables $field1 although register_globals was switched on! Needed to work with $HTTP_POST_VARS['field1'] and $HTTP_POST_FILES['userfile'] to get the values.
o.k., here's the script sending the header:
$f=fsockopen($server,80,$errno,$errstr,30);
fwrite($f,$header);
fclose($f);
The receiving script is as easy 🙂 The file was uploaded to $HTTP_POST_FILES['userfile']['tmp_name'] and the variables were named as mentioned above.
Hope, it prevents spending another afternoon to figure out a file-upload this way 🙂

Похожее:  Личный кабинет Пенсионного фонда РФ для физлиц - вход и регистрация на официальном сайте

02-mar-2007 03:01


HTTP/1.1 requires that all clients support chunked transfer encoding. If you don't want to implement that and just want something simple, make HTTP/1.0 requests instead:
<?php
...
fputs("GET $path HTTP/1.0rn");
fputs("Host: $hostrn");
...etc..
?>

mikebnospam


Hey, why were my comments regarding fsockopen connection timeouts taken out? I'm sure they would have been very useful to other users.
fsockopen (on FreeBSD and probably OpenBSD) will ignore the connection timeout parameter, and hang for several minutes if it can't connect for a variety of reasons (no DNS resolve, host down, extreme firewall setups). Use curl instead until a solution is found (i spent days on this issue)

edwin


jk


here is my contribution for parsing chunked data.
please note: this function simply handles the RESPONSE, not the HEADERS, it would be your job to check the headers for 'Transfer-Encoding: chunked' field:
<?php
function parseChunked($response) {
$do = true;
$return = "";
$size = NULL;
while($do) {
// suppress warnings w/ @ if offset not in string (past end)
$pos = @strpos($response, "rn", 0);
if(!($pos === false) && $size === NULL) {
// we found CRLF, get len from hex
$size = hexdec(substr($response, 0, $pos));

     // get the actual chunk-len, reset $response, $size
$return .= substr($response, $pos 2, $size);
$response = substr($response, ($pos 2) $size);
$size = NULL;
}
else {
$do = false;
} // end if/else
} // end while
return $return;
} // end function parseChunked()
?>
Any recomendations or improvements please post

bimal dot das


Here is how to POST a form action to a SSL server's cgi and retrieve output with pfsockopen
<?php
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);
# working vars
$host = 'www.example.com';
$service_uri = '/cgi-bin/processACT';
$vars ='code=22&act=TEST';
# compose HTTP request header
$header = "Host: $hostrn";
$header .= "User-Agent: PHP Scriptrn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: ".strlen($vars)."rn";
$header .= "Connection: closernrn";
$fp = pfsockopen("ssl://".$host, 443, $errno, $errstr);
if (!$fp) {
echo "$errstr ($errno)<br/>n";
echo $fp;
} else {
fputs($fp, "POST $service_uri  HTTP/1.1rn");
fputs($fp, $header.$vars);
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>

jack


redvader


xbiron


Header to declare cookie :
<?php
/* [other headers] */
# Syntax => Cookie: name=value; name=value
# Never finish with ';'
$header.= "Cookie: name_cookie1=value_cookie1; name_cookie2=value_cookie2rn";
?>
Header to create cookie :
<?php
/* [other headers] */
# Syntax => Set-Cookie: name=value[; path=PATH][; expires=DATE][; domain=DOMAIN_NAME][; secure]
# DATE format : Day, dd-Mmm-yy hh:ii:ss GMT
# Never finish with ';'
$header.= "Set-Cookie: name_cookie=value_cookie; path=; Friday, 13-Jan-03 12:00:00 GMTrn";
?>

jbr


Handling chunked data needs careful handling, because the data can also be compressed inside the chunked data, and chunked data can have many parts, so you need to watch for that. Here a simple example that uses one function decode_header(); to build the header into a key => value array, so it makes it easy to test for the content and transfer types inside the decode_body(); function!
<?php
function decode_header ( $str )
{
$part = preg_split ( "/r?n/", $str, -1, PREG_SPLIT_NO_EMPTY );
$out = array ();
for ( $h = 0; $h < sizeof ( $part ); $h )
{
if ( $h != 0 )
{
$pos = strpos ( $part[$h], ':' );
$k = strtolower ( str_replace ( ' ', '', substr ( $part[$h], 0, $pos ) ) );
$v = trim ( substr ( $part[$h], ( $pos 1 ) ) );
}
else
{
$k = 'status';
$v = explode ( ' ', $part[$h] );
$v = $v[1];
}
if ( $k == 'set-cookie' )
{
$out['cookies'][] = $v;
}
else if ( $k == 'content-type' )
{
if ( ( $cs = strpos ( $v, ';' ) ) !== false )
{
$out[$k] = substr ( $v, 0, $cs );
}
else
{
$out[$k] = $v;
}
}
else
{
$out[$k] = $v;
}
}
return $out;
}
function decode_body ( $info, $str, $eol = "rn" )
{
$tmp = $str;
$add = strlen ( $eol );
$str = '';
if ( isset ( $info['transfer-encoding'] ) && $info['transfer-encoding'] == 'chunked' )
{
do
{
$tmp = ltrim ( $tmp );
$pos = strpos ( $tmp, $eol );
$len = hexdec ( substr ( $tmp, 0, $pos ) );
if ( isset ( $info['content-encoding'] ) )
{
$str .= gzinflate ( substr ( $tmp, ( $pos $add 10 ), $len ) );
}
else
{
$str .= substr ( $tmp, ( $pos $add ), $len );
}
$tmp = substr ( $tmp, ( $len $pos $add ) );
$check = trim ( $tmp );
} while ( ! empty ( $check ) );
}
else if ( isset ( $info['content-encoding'] ) )
{
$str = gzinflate ( substr ( $tmp, 10 ) );
}
return $str;
}
if ( ( $io = fsockopen( "www.yahoo.com", 80, $errno, $errstr, 5 ) ) !== false )
{
$send  = "GET / HTTP/1.1rn";
$send .= "Host: www.yahoo.comrn";
$send .= "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204rn";
$send .= "Referer: http://www.yahoo.com/rn";
$send .= "Accept: text/xml,application/xml,application/xhtml xml,";
$send .= "text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,";
$send .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1rn";
$send .= "Accept-Language: en-us, en;q=0.50rn";
$send .= "Accept-Encoding: gzip, deflate, compress;q=0.9rn";
$send .= "Connection: Closernrn";
fputs ( $io, $send );
$send = '';
do
{
$send .= fgets ( $io, 4096 );
} while ( strpos ( $send, "rnrn" ) === false );
$info = decode_header ( $send );
$send = '';
while ( ! feof ( $io ) )
{
$send .= fread ( $io, 8192 );
}
fclose ( $io );
$send = decode_body ( $info, $send );
echo '<h3>Header Array</h3>';
echo '<pre>';
print_r ( $info );
echo '</pre>';
echo '<h3>Document Body</h3>';
echo $send;
}
?>

elemental21


corey


For those of you trying to POST cookies, use the header:
"Cookie: cookiename=cookievaluern";
I haven't tried this for multiple cookies, I would assume you just add another Cookies: line to your header var.

jasoncernivsky


For IPN I recommend to customize a nice framework called LibePal. It has been very handy here. We currently base more than 10 customer sites with the same tool. It works by CURL I think.

31-may-2006 06:42


davem


For data returned as "chunked" you cannot simply loop through the file with fgets and return a correct response.
This function has worked for me, any improvements welcome:
//parse response text out of chunked response
function ParseChunked($response)
{
$response = explode("rn",$response);
for($i=0; $i<count($response); $i )
if(hexdec($response[$i])==strlen($response[$i 1]))
$return.=$response[ $i];
return $return;
}

aska


easy get UIDL.
A code is better than the feof.
<?php
$fp = fsockopen($host, 110, $errno, $errstr, 5);
if ($fp > 0) {
fread($fp,1024);
fputs($fp, "USER $userrn");
fread($fp,1024);
fputs($fp, "PASS $passrn");
fread($fp,1024);
fputs($fp, "UIDLrn");
fgets($fp,1024);
do {
$line = rtrim(fgets($fp, 1024));
if ($line == '.') break;
list(, $UIDL) = split(' ', $line, 2);
echo $UIDL;
} while ($line != '.');

fputs($fp, "QUITrn");
}
fclose($fp);
?>

18-feb-2006 08:49


Dante
28-Dec-2005 06:42
If you're using code like the manual's example, it is a good idea to keep using HTTP/1.0 instead of changing it to HTTP/1.1. Using HTTP/1.1 with fsockopen sometimes results in junk before and after the body content (but not in the headers).
This is not actually true, if you are using HTTP/1.1, you will most likely be receiving chunked data. The 'junk' that you are seeing is probably the size of the chunks in hex.

nospam


l0gic


kiki_ef


Additional ICQ status request over proxy
<?php
function icq_uin($uin)
{
if (! is_numeric($uin))
return false;
$proxy_name = 'proxy.mydomain.de';
$proxy_port = 8080;
$proxy_user = "";
$proxy_pass = "";
$proxy_cont = '';
$request_url = "http://status.icq.com/online.gif?icq=$uin";
$proxy_fp = fsockopen($proxy_name, $proxy_port);
if (!$proxy_fp)
return false;
fputs($proxy_fp, "GET $request_url HTTP/1.0rnHost: $proxy_namern");
fputs($proxy_fp, "Proxy-Authorization: Basic ". base64_encode ("$proxy_user:$proxy_pass")."rnrn");
while(!feof($proxy_fp)){
$proxy_cont .= fread($proxy_fp,4096);
}
fclose($proxy_fp);
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"rnrn") 4);
if (strstr($proxy_cont, 'online1'))
return 'online';
if (strstr($proxy_cont, 'online0'))
return 'offline';
if (strstr($proxy_cont, 'online2'))
return 'disabled';
}
echo "User is ".icq_uin(123456789012345);
?>
Based on http://de2.php.net/manual/de/function.fopen.php#53090
Thanx

parming


A pretty crude, but somewhat useful force-ping of the nearest network may come in handy for other mediocre coders like me. It returns an array of all replying boxes according to your $port choice (where, for reference, 139 targets all network cards and 3306 only running mysql apps). Keep the $timeout under 1 and the function can run in-under a second. Obvious limitations apply.
$ip = implode(".", array_slice(explode(".", $_SERVER["SERVER_ADDR"]), 0, 3)) . ".";
for ($i =0; $i < 255; $i )
if (@fsockopen($ip . $i, $port, $err, $errstr, $timeout))
$online[] = $ip . $i;
The function can be expanded with additional for-loops, but I can't see the direct purpose of pinging everything-there-is.
Daniel Parming

sir_reality2001


<?
// This is a modification to the script I submitted below.
// This script is an example of posting multiple files using
// fsockopen.
// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.
// This script is for example purposes only and could/should be improved upon.
$host='targethost';
$port=80;
$path='/test/socket/file_upload/receive_files.php';
// the file you want to upload
$file_array[0] = "dingoboy.gif"; // the file
$file_array[1] = "dingoboy2.gif"; // the file
$file_array[2] = "dingoboy3.gif"; // the file
$content_type = "image/gif"; // the file mime type
//$content_type = "text/plain";
//echo "file_array[0]:$file_array[0]
";
srand((double)microtime()*1000000);
$boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);
$data = "--$boundary";
for($i=0;$i<count($file_array);$i ){
$content_file = join("", file($file_array[$i]));
$data.="
Content-Disposition: form-data; name="file".($i 1).""; filename="$file_array[$i]"
Content-Type: $content_type
$content_file
--$boundary";
}
$data.="--rnrn";
$msg =
"POST $path HTTP/1.0
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: ".strlen($data)."rnrn";
$result="";
// open the connection
$f = fsockopen($host, $port);
fputs($f,$msg.$data);
// get the response
while (!feof($f)) $result .= fread($f,32000);
fclose($f);
?>

richard dot lajaunie


<?
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr on the same page
**************************************************************/
if ( array_key_exists(1, $argv) ){
$cfgServer = $argv[1];
}else{
echo "ex: 'php test.php 10.0.0.0' n";
exit;
}
$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;
$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr), $cfgTimeOut);
if(!$usenet){
echo "Connexion failedn";
exit();
}else{
echo "Connectedn";
fputs ($usenet, "passwordrn");
fputs ($usenet, "enrn");
fputs ($usenet, "passwordrn");
fputs ($usenet, "sh mac-address-tablern");
fputs ($usenet, " "); // this space bar is this for long output
// this skip non essential text
$j = 0;
while ($j<16){
fgets($usenet, 128);
$j ;
}
stream_set_timeout($usenet, 2); // set the timeout for the fgets
$j = 0;
while (!feof($usenet)){
$ret = fgets($usenet, 128);
$ret = str_replace("r", '', $ret);
$ret = str_replace("n", "", $ret);
if  (ereg("FastEthernet", $ret)){
echo "$ret n";
}
if (ereg('--More--', $ret) ){
fputs ($usenet, " "); // for following page
}
$info = stream_get_meta_data($usenet);
if ($info['timed_out']) {
$j ;
}
if ($j >2){
fputs ($usenet, "lo");
break;
}
}
}
echo "End.rn";
?>

Php post data with fsockopen

I am attempting to post data using fsockopen, and then returning the result.
Here is my current code:

<?php
$data="stuff=hoorahrn";
$data=urlencode($data);

$fp = fsockopen("www.website.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />n";
} else {
    $out = "POST /script.php HTTP/1.0rn";
    $out .= "Host: www.webste.comrn";
    $out .= 'Content-Type: application/x-www-form-urlencodedrn';
    $out .= 'Content-Length: ' . strlen($data) . 'rnrn';
    $out .= "Connection: Closernrn";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?> 

It is supposed to echo the page, and it is echoing the page, but here is the script for script.php

<?php
echo "<br><br>";    
$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];  
 parse_str( $raw_data, $_POST );

//test 1
var_dump($raw_data);
echo "<br><br>":
//test 2
print_r( $_POST );  
?>

The outcome is:

HTTP/1.1 200 OK Date: Tue, 02 Mar 2022
22:40:46 GMT Server: Apache/2.2.3
(CentOS) X-Powered-By: PHP/5.2.6
Content-Length: 31 Connection: close
Content-Type: text/html; charset=UTF-8
string(0) “” Array ( )

What do I have wrong? Why isn’t the variable posting its data?

1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)
Загрузка...

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector