Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

fsockopen

(PHP 3, PHP 4, PHP 5)

fsockopen --  Open Internet or Unix domain socket connection

Description

resource fsockopen ( string target [, int port [, int &errno [, string &errstr [, float timeout]]]] )

Initiates a socket connection to the resource specified by target. PHP supports targets in the Internet and Unix domains as described in Прил. O. A list of supported transports can also be retrieved using stream_get_transports().

Замечание: If you need to set a timeout for reading/writing data over the socket, use stream_set_timeout(), as the timeout parameter to fsockopen() only applies while connecting the socket.

As of PHP 4.3.0, if you have compiled in OpenSSL support, you may prefix the hostname with either 'ssl://' or 'tls://' to use an SSL or TLS client connection over TCP/IP to connect to the remote host.

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()).

If the call fails, it will return FALSE and if the optional errno and errstr arguments are present they will be set to indicate the actual system level error that occurred in the system-level connect() call. If the value returned in errno is 0 and the function returned FALSE, it is an indication that the error occurred before the connect() call. This is most likely due to a problem initializing the socket. Note that the errno and errstr arguments will always be passed by reference.

Depending on the environment, the Unix domain or the optional connect timeout may not be available.

The socket will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

Пример 1. fsockopen() Example

<?php
$fp
= fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!
$fp) {
    echo
"$errstr ($errno)<br />\n";
} else {
   
$out = "GET / HTTP/1.1\r\n";
   
$out .= "Host: www.example.com\r\n";
   
$out .= "Connection: Close\r\n\r\n";

   
fwrite($fp, $out);
    while (!
feof($fp)) {
        echo
fgets($fp, 128);
    }
   
fclose($fp);
}
?>
The example below shows how to retrieve the day and time from the UDP service "daytime" (port 13) in your own machine.

Пример 2. Using UDP connection

<?php
$fp
= fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!
$fp) {
    echo
"ERROR: $errno - $errstr<br />\n";
} else {
   
fwrite($fp, "\n");
    echo
fread($fp, 26);
   
fclose($fp);
}
?>

Внимание

UDP sockets will sometimes appear to have opened without an error, even if the remote host is unreachable. The error will only become apparent when you read or write data to/from the socket. The reason for this is because UDP is a "connectionless" protocol, which means that the operating system does not try to establish a link for the socket until it actually needs to send or receive data.

Замечание: При указании числового адреса IPv6 (например, fe80::1) вы должны заключать его в квадратные скобки. Например, tcp://[fe80::1]:80.

Замечание: The timeout parameter was introduced in PHP 3.0.9 and UDP support was added in PHP 4.

See also pfsockopen(), stream_set_blocking(), stream_set_timeout(), fgets(), fgetss(), fwrite(), fclose(), feof(), and the Curl extension.



gethostbyaddr> <dns_get_record
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
fsockopen
parming at gmail dot com
15-Oct-2007 02:26
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
anarchy
04-Sep-2007 06:34
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....
corey at detoxservers dot com
02-Sep-2007 12:47
For those of you trying to POST cookies, use the header:
"Cookie: cookiename=cookievalue\r\n";
I haven't tried this for multiple cookies, I would assume you just add another Cookies: line to your header var.
bradland at umich dot edu
23-Jul-2007 09:32
I was having trouble doing an https in fopen and with fsockopen where the address had ssl://.  I was getting error code 114 in the log.  After much research i found that there was some ssl conflict trouble with MySQL 5.0.20-5.0.33.  It had some functions that were interfering with openssl that showed up in the php install.

http://bugs.mysql.com/bug.php?id=21930
http://bugs.mysql.com/bug.php?id=19289
warezthebeef at gmail dot com
17-Jul-2007 04:37
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!
aska at unit-mse dot jp
03-Jul-2007 06:58
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 $user\r\n");
   
fread($fp,1024);
   
fputs($fp, "PASS $pass\r\n");
   
fread($fp,1024);
   
fputs($fp, "UIDL\r\n");
   
fgets($fp,1024);
    do {
       
$line = rtrim(fgets($fp, 1024));
        if (
$line == '.') break;
        list(,
$UIDL) = split(' ', $line, 2);
        echo
$UIDL;
    } while (
$line != '.');
   
   
fputs($fp, "QUIT\r\n");
}
fclose($fp);

?>
Alexander Wegener
26-May-2007 07:29
To check if a Url is Online (with http and https)
Using @fgets to hide Warning when using SSL
(Bug: "Warning: function.fgets SSL: fatal protocol error", http://bugs.php.net/bug.php?id=23220)

<?php

   
function isOnline($url) {
        if (!
$url_info = parse_url($url)) {
            return
false;   
        }
       
        switch (
$url_info['scheme']) {
            case
'https':
               
$scheme = 'ssl://';
               
$port = 443;
                break;
            case
'http':
            default:
               
$scheme = '';
               
$port = 80;   
        }
       
       
$data = "";
       
$fid = @fsockopen($scheme . $url_info['host'], $port, $errno, $errstr, 30);
        if (
$fid) {
           
fputs($fid, 'HEAD ' . (isset($url_info['path'])? $url_info['path']: '/') . (isset($url_info['query'])? '?' . $url_info['query']: '') . " HTTP/1.0\r\n" .
                       
"Connection: close\r\n" .
                       
'Host: ' . $url_info['host'] . "\r\n\r\n");   
            while (!
feof($fid)) {
               
$data .= @fgets($fid, 128);
            }
           
fclose($fid);
            return !empty(
$data);
        } else {
            return
false;
        }
    }

?>
martjean77 at hot dot sapm dot mail dot com
16-May-2007 07:44
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 = "\r\n" )
{
  $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;
}
02-Mar-2007 07: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.0\r\n");
fputs("Host: $host\r\n");
...
etc..
?>
jbr at ya-right dot com
01-Mar-2007 08:17
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 = "\r\n" )
{
   
$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.1\r\n";
   
$send .= "Host: www.yahoo.com\r\n";
   
$send .= "User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20021204\r\n";
   
$send .= "Referer: http://www.yahoo.com/\r\n";
   
$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.1\r\n";
   
$send .= "Accept-Language: en-us, en;q=0.50\r\n";
   
$send .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
   
$send .= "Connection: Close\r\n\r\n";

   
fputs ( $io, $send );

   
$send = '';

    do
    {
       
$send .= fgets ( $io, 4096 );

    } while (
strpos ( $send, "\r\n\r\n" ) === 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;

}

?>
ryan1_00 at hotmail dot com
29-Jan-2007 07:52
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).
            }
        } 
    }
}
v13+phpnet at it dot teithe dot gr
24-Jan-2007 03:01
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 $username\n";
    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 $password\n";
    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);
}
?>
jk at ricochetsolutions dot com
19-Dec-2006 07:20
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, "\r\n", 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
04-Dec-2006 08: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 :P

<?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.1\r\n";
       
$requestHeader.= "Host: ".$host."\r\n";
       
$requestHeader.= "User-Agent:      Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0\r\n";
       
$requestHeader.= "Content-Type: application/x-www-form-urlencoded\r\n";

        if (
$method == "POST")
        {
           
$requestHeader.= "Content-Length: ".strlen($data)."\r\n";
        }
       
       
$requestHeader.= "Connection: close\r\n\r\n";
       
        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);
    }

?>
jasoncernivsky at gmail dot com
29-Oct-2006 11:13
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.
albertohf at hotmail dot com
03-Aug-2006 09:01
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.1\r\n";
            $salida.="Host: $host\r\n";
            $salida.="User-Agent: PHP Script\r\n";
            $salida.="Content-Type: application/x-www-form-urlencoded\r\n";
            $salida.="Content-Length: ".strlen($postdata)."\r\n";
            $salida.="Connection: close\r\n\r\n";
            $salida.=$postdata;
            fwrite($da, $salida);
                     while (!feof($da))
                $response.=fgets($da, 128);
            $response=split("\r\n\r\n",$response);
            $header=$response[0];
            $responsecontent=$response[1];
            if(!(strpos($header,"Transfer-Encoding: chunked")===false)){
                $aux=split("\r\n",$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
tylernt at bigfoot dot com
18-Jul-2006 11:57
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.
bimal dot das at maxartists dot com
07-Jun-2006 11:22
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: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".strlen($vars)."\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = pfsockopen("ssl://".$host, 443, $errno, $errstr);
if (!
$fp) {
   echo
"$errstr ($errno)<br/>\n";
   echo
$fp;
} else {
   
fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
   
fputs($fp, $header.$vars);
   
fwrite($fp, $out);
    while (!
feof($fp)) {
        echo
fgets($fp, 128);
    }
   
fclose($fp);
}

?>
30-May-2006 10:42
For everyone complaining about wasting their time because the socket remained open when using HTTP 1.1

Why don't you try and read the RFC for HTTP before you start trying to implement a simple HTTP client?

http://www.w3.org/Protocols/rfc2616/rfc2616.html
dmitry dot polushkin at gmail dot com
22-May-2006 05:45
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.1\r\nHost: www.php.net\r\nConnection: Keep-Alive\r\n\r\n");
   
$data = '';
    while(!
feof($fp)) {
       
$data .= fread($fp, 4096);
        if(
substr($data, -9)=="\r\n\r\n0\r\n\r\n") {
            exit;
        }
    }
}
echo
$data;
?>
yourpicture at hotpop dot com
04-May-2006 11:30
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<br>";
       
// 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<br>";
            return
0;
        }
        else {
           
// copied method for PING like time operation
           
$status = socket_get_status($handle);
            echo
"Opened ProxyServer $ProxyServer<br>";
           
           
//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 this\n");
            if(!
$write){
                return
0;
            }
           
            echo
"Try To Read<br>";
           
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<br>";
           
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<br>";
       return
0;
    }

   
$old_error_handler = set_error_handler("userErrorHandler");

   
$time = Ping();
    echo
"Time=$time<br>";
    echo
"Done Checking<br>";
?>

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
yadiutama_skom at yahoo dot com
07-Apr-2006 02:09
This is a simple example for sending and retrieve SOAP message by using fsockopen:

<?php
$fp
= @fsockopen("www.example.com", 80, $errno, $errstr);
if (!
$fp) {
    echo
"$errstr ($errno)<br />\n";
} else {

$soap_out  = "POST /example/exampleServer.php HTTP/1.0\r\n";
$soap_out .= "Host: www.example.com\r\n";
$soap_out .= "User-Agent: MySOAPisOKGuys \r\n";
$soap_out .= "Content-Type: text/xml; charset=ISO-8859-1\r\n";
$soap_out .= "Content-Length: 512\r\n\r\n";
$soap_out .= '<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns5973:contact xmlns:ns5973="http://tempuri.org">
<__numeric_0><id  xsi:nil="true"/></__numeric_0>
</ns5973:contact>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>'
;

   
fputs($fp, $soap_out, strlen($soap_out));  // send request SOAP

   
echo "<xmp>".$out."</xmp>";

    while (!
feof($fp)) {
       
$soap_in . = fgets($fp, 100);
    }

    echo
"<xmp>$soap_in</xmp>";   //display response SOAP

   
fclose($fp);
}
?>

And this is an example result:

POST /soap/example/contactServer.php HTTP/1.0
Host: www.example.com
User-Agent: MySOAPisOKGuys
Content-Type: text/xml; charset=ISO-8859-1
Content-Length: 512
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body><ns5973:contact
xmlns:ns5973="http://tempuri.org"><__numeric_0><id
xsi:nil="true"/></__numeric_0></ns5973:contact>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

HTTP/1.1 200 OK
Date: Thu, 06 Apr 2006 07:03:26 GMT
Server: Apache/1.3.23 (Win32)
X-Powered-By: PHP/4.1.1
X-SOAP-Server: MySOAPisOKGuys
Content-Length: 625
Connection: close
Content-Type: text/xml; charset=ISO-8859-1
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body><ns1:contactResponse
xmlns:ns1="http://tempuri.org">
<return xsi:type="xsd:string">
</return>
</ns1:contactResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Duukkis
27-Feb-2006 05:13
Lots of tries and lots of reading http-headers...

If you want to post $_POST vars and (in this case) one file named userfile to $remote_server and $remote_url.

<?php
       
// get the necessary data
       
$file_name = $_FILES['userfile']['name'];     // the file
       
$tmp_name = $_FILES['userfile']['tmp_name'];     // the file
       
$content_type = $_FILES['userfile']['type'];     // the file mime type
       
       
srand((double)microtime()*1000000);
       
$boundary = "---------------------".substr(md5(rand(0,32000)),0,10);
       
       
// Build the header
       
$header = "POST $remote_url HTTP/1.0\r\n";
       
$header .= "Host: $remote_server\r\n";
       
$header .= "Content-type: multipart/form-data, boundary=$boundary\r\n";
       
// attach post vars
       
foreach($_POST AS $index => $value){
           
$data .="--$boundary\r\n";
           
$data .= "Content-Disposition: form-data; name=\"".$index."\"\r\n";
           
$data .= "\r\n".$value."\r\n";
           
$data .="--$boundary\r\n";
        }
       
// and attach the file
       
$data .= "--$boundary\r\n";
       
$content_file = join("", file($tmp_name));
       
$data .="Content-Disposition: form-data; name=\"userfile\"; filename=\"$file_name\"\r\n";
       
$data .= "Content-Type: $content_type\r\n\r\n";
       
$data .= "".$content_file."\r\n";
       
$data .="--$boundary--\r\n";
       
$header .= "Content-length: " . strlen($data) . "\r\n\r\n";
                
// Open the connection
       
$fp = fsockopen($remote_server, 80);
       
// then just
       
fputs($fp, $header.$data);
       
fclose($fp);
?>
18-Feb-2006 12: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.
ittasks at gmail dot com
15-Feb-2006 04:02
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:<br><pre>\n".$mycookies."\n</pre>";
//$body =PostPage("www.yourdomain.com/coolpage.asp",
//"action=zzz",$mycookies);
//echo "<br>Body:<br>\n".$body."\n";
//im using get page - so it goes like this:
$opts = array('http'=>array('method'=>"GET",
'header'=>"Accept-language: en\r\nCookie: ".$mycookies."\r\n" ));
$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.1\r\nHost: $host\r\n";
$post.="Content-type: application/x-www-form-";
$post.="urlencoded\r\n${others}";
$post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
$post.=strlen($query)."\r\nConnection: close\r\n\r\n$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 = "\r\n";
  
$path='/'.(implode('/',$path));
  
$post="POST $path HTTP/1.1\r\nHost: $host\r\n";
$post.="Content-type: application/x-www-form-urlencoded\r\n${others}";
$post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
$post.=strlen($query)."\r\nConnection: close\r\n\r\n$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
na8ur
15-Jan-2006 04:41
if you send some header information to any server eg. sending cookie data, don't forget to have \r\n\r\n (double new line) at the end of your header data.
davem
05-Jan-2006 09:25
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("\r\n",$response);
    for($i=0; $i<count($response); $i++)
        if(hexdec($response[$i])==strlen($response[$i+1]))
          $return.=$response[++$i];
    return $return;
}
Dante
27-Dec-2005 12: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).
SysCo/al - developer [at] sysco[dot] ch
24-Dec-2005 05:41
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');
?>
sivann at cs dot ntua dot gr
09-Dec-2005 07:40
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)<br>\n";
   exit;
}
else {
   $out = "$remport, 80\r\n";
   fwrite($fp, $out);
   $answer=fgets($fp, 128);
}
fclose($fp);
$ansparts=explode(":",$answer);
$user=chop($ansparts[3]);
echo "You are $user@$remip:$remport";

?>
Kiki_EF
27-Oct-2005 12:20
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.0\r\nHost: $proxy_name\r\n");
   
fputs($proxy_fp, "Proxy-Authorization: Basic ". base64_encode ("$proxy_user:$proxy_pass")."\r\n\r\n");
    while(!
feof($proxy_fp)){
       
$proxy_cont .= fread($proxy_fp,4096);
    }
   
fclose($proxy_fp);
   
$proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+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
alex at renesource dot lv
29-Sep-2005 12:52
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);

?>
robin at pozytron dot com
21-Aug-2005 03:38
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.
l0gic at l0gic dot net
12-Aug-2005 11:54
After a little experimenting, I worked out how to reliably handle chunked HTTP/1.1 data. The following code assumes a connection has already been opened as $fp, and the response header has been read into the array $header. A loop is used to read data until the entire chunk length has been read, due to fsockopen()'s tendency to stop reading when a new packet is received. Please note that I have not put this code through thorough testing; this is merely to demonstrate the methodology.

if (isset($header['Transfer-Encoding'])) {
   
    // Read the length of the current chunk
    while ($chunk_length = hexdec(fgets($fp))) {
       
        // Initialize counter and buffer
        $read_length = 0;
        $data = NULL;
       
        // Read $chunk_length bytes of data
        while ($read_length < $chunk_length) {
           
            $data .= fread($fp, $chunk_length - $read_length);
            $read_length = strlen($data);
           
            }
       
        // Output the data read
        echo $data;
       
        }
}
dna at revold-design dot de
10-Aug-2005 05:04
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.0\r\n"
             
."Host: web.icq.com\r\n"
             
."Connection: close\r\n\r\n";
   
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);
?>
Jeremy
05-Jul-2005 11:52
The only think wrong with richard burton's code as regarding apache is that
$byte != "\\r" should be
$byte == "\r"
richard dot lajaunie at cote-azur dot cci dot fr
19-May-2005 12:10
<?
/************************************************************
* 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 failed\n";
       exit();
}else{
       echo "Connected\n";
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "en\r\n");
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "sh mac-address-table\r\n");
       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.\r\n";
?>
saul dot dobney at dobney dot com
19-Apr-2005 08:40
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 \r\n on the end of it and won't give you a valid path in the next iteration otherwise. A six hour bug.

Saul Dobney
nospam at cronjob dot de
17-Apr-2005 05:06
Be careful if you open a lot of sockets in one php-file!
I had a script which checked a lot of domains and opened sockets to the whois-server. Even that I closed the connections after I checked a domain (fclose), the sockets seemed to stay open. After a while (about 1000 connections) the php-script couldn't open any more sockets.
It took a while to fix this problem. I did this by writing a script which started the check-scripts with wget (or lynx). I started 5 scripts parallel and just checked 20 domains. After that new 5 scripts where opened. That helped me not to open too many sockets in one php-file because when a php-script ends, all open sockets are closed.

Example:

start.php:
<?php
ignore_user_abort
(true);
for(
$i=0; $i<100; $i++) {
    echo
$i."- "; flush();
   
$exec_string = 'lynx http://domain.tld/whois.php &';
   
$output = `$exec_string`;
   
sleep(10);
   
$exec_string = 'killall lynx';
   
$output = `$exec_string`;
}
?>

whois.php:
<?php
ignore_user_abort
(true);
for(
$i=0; $i<50; $i++) {
   
fsockopen(whois.server...);
   
// here you process the whois-things
}
?>

Hope this'll help some people!
ahauk at NO-SPAM dot synergynt dot net
28-Mar-2005 02:38
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 $user\n");
       
$output = fgets($connection, 128);
       
fputs($connection, "pass $pass\n");
       
$output = fgets($connection, 128);
        while(
$low < $high - 1) {
           
$mid = floor(($low + $high) / 2);
           
fputs($connection, "list $mid\n");
           
$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 $count\n");
           
fgets($connection, 128);
           
$count = $count + 1;
        }
       
fputs($connection, "quit\n");
    }
   
fclose($connection);
    print
"Successfully removed $limit messages.";
?>
JMPZ
28-Feb-2005 09:04
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.
redvader at yandex dot ru
25-Feb-2005 07:34
here are some fixes to code by
edwin at bitstorm dot org
they might seem silly, but still useful in some cases

<?php
 
function fetchURL( $url ) {
  
$url_parsed = parse_url($url);
  
$host = $url_parsed["host"];
  
$port = $url_parsed["port"];
    if (
$port==0)
      
$port = 80;
  
$path = $url_parsed["path"];

  
//if url is http://example.com without final "/"
   //I was getting a 400 error
   
if (empty($path))
   
$path="/";

   
//redirection if url is in wrong format
   
if (empty($host)):
   
$host="www.somesite.com";
   
$path="/404.shtml";
    endif;

   if (
$url_parsed["query"] != "")
      
$path .= "?".$url_parsed["query"];
  
$out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
  
$fp = fsockopen($host, $port, $errno, $errstr, 30);
  
fwrite($fp, $out);
  
$body = false;
   while (!
feof($fp)) {
   echo
fgets($fp, 128);
   }
  
fclose($fp);
   return
$in;
}

fetchURL($address);
?>
dante at dantecubed dot com
23-Feb-2005 04:00
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.
konrad dot meyer at gmail dot com
12-Feb-2005 01:34
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, gzip\r\n"
function post($host,$query,$others=''){
   
$path=explode('/',$host);
   
$host=$path[0];
    unset(
$path[0]);
   
$path='/'.(implode('/',$path));
   
$post="POST $path HTTP/1.1\r\nHost: $host\r\nContent-type: application/x-www-form-urlencoded\r\n${others}User-Agent: Mozilla 4.0\r\nContent-length: ".strlen($query)."\r\nConnection: close\r\n\r\n$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;
}
?>
edwin at bitstorm dot org
02-Dec-2004 05:50
Here's a function to just fetch the contents behind an URL.

<?php
function fetchURL( $url ) {
   
$url_parsed = parse_url($url);
   
$host = $url_parsed["host"];
   
$port = $url_parsed["port"];
    if (
$port==0)
       
$port = 80;
   
$path = $url_parsed["path"];
    if (
$url_parsed["query"] != "")
       
$path .= "?".$url_parsed["query"];

   
$out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

   
$fp = fsockopen($host, $port, $errno, $errstr, 30);

   
fwrite($fp, $out);
   
$body = false;
    while (!
feof($fp)) {
       
$s = fgets($fp, 1024);
        if (
$body )
           
$in .= $s;
        if (
$s == "\r\n" )
           
$body = true;
    }
   
   
fclose($fp);
   
    return
$in;
}
?>
Simon Riget at paragi.com
17-Nov-2004 08:25
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)<br>\r\n";
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 this\n");
        if(!$write){
            echo "Error in writing to socked<br>\r\n";
            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<br>\r\n";
        else   
            echo " : Round trip = ".round($laptime,3)." s<br>\r\n";
    }
    fclose($handle);
}
?>
michiel at parse dot nl
25-Oct-2004 04:42
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)<br>\n";
    }
    else
    {
        fputs ($fp, "GET /".$url['path'].($url['query'] ? '?'.$url['query'] : '')." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
        $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];
    }
}
?>
elemental21 at hotmail dot com
08-Oct-2004 07:23
Found this php class to use telnet from here:
http://cvs.adfinis.ch/cvs.php/phpStreamcast/telnet.class.php

There's no docs and a lot of it's in french though so maybe it will help
someone to have my working code. This code is used to telnet into a
pix and execute the "shun" command.

//-------telnet.class.php usage example---------
                $telnet = new telnet;
// Next line is for logging. 
//By default you need to create a folder called /log and give it the
//rights your webserver is running.
                $telnet->setLog(1,"mylog");
                $telnet->set_host("myhost.myplace.com");
//You need to set the prompt to what you know its going to be,
//then call wait_prompt...which waits for what you just set
                $telnet->set_prompt("Password: ");
                $telnet->connect();
                $telnet->wait_prompt();
                $telnet->write("mypassword");
//Have to change the prompt...in my example this is the
//prompt that a pix will change to after loggin in.
                $telnet->set_prompt("pix> ");
                $telnet->wait_prompt();
                $telnet->write("en");
                $telnet->set_prompt("Password: ");
                $telnet->wait_prompt();
                $telnet->write("enable_password");
//When you go into enable mode in a pix the prompt changes
                $telnet->set_prompt("pix# ");
                $telnet->wait_prompt();
                $telnet->write("shun " . $shun_address);
                $telnet->wait_prompt();
                $telnet->write("clear xlate");
                $telnet->wait_prompt();
                $telnet->write("write mem");
                $telnet->wait_prompt();
                $telnet->write("exit");
                $telnet->disconnect();
mikebNOSPAM at xamo dot com
29-Sep-2004 04:17
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)
bjorn (at) ahusonline dot com
21-May-2004 04:50
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,"user\r");
usleep(125000);
fputs($fp,"users.pass\r");
usleep(125000);
# root looks nice
fputs($fp,"su\r");
usleep(125000); # takes some time, we had to wait
fputs($fp,"root.pass\r");

# some tests
fputs($fp,"ifconfig\r");       
fputs($fp,"echo year telnet php connect works|wall\r");

# 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", "<br>", $output);
echo
$output;
fclose($fp);
?>
alex at renesource dot lv
16-Mar-2004 11:07
Set up SSL connection to server that requires client certificate:

Convert client certificate from *.pfx (pkcs12) into*.pem with openssl (if needed):

> openssl pkcs12 -in keys.pfx -out keys.pem

PHP:

<?php
$context
= stream_context_create();
$result = stream_context_set_option($context, 'ssl', 'local_cert', '/path/to/keys.pem');
$result = stream_context_set_option($context, 'ssl', 'passphrase', 'pass_to_access_keys');

$socket = fsockopen('ssl://'.$host, 443, $errno, $errstr, 30, $context);
?>
jack at jtr dot de
16-Feb-2004 02:05
Here is a function for testing a website/URI for availability:

<?php
   
/*
    * @return boolean
    * @param  string $link
    * @desc  
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571