Php-implemented ping port function instance and phpping port instance
This example describes the ping port function implemented by php. Share it with you for your reference.
The specific implementation code is as follows:
Copy codeThe Code is as follows:
<? Php
/*
* @ Author xujiajay
* @ Date 2010-10-7
* @ Function: the php function that can ping the port.
*
*/
Error_reporting (E_ERROR );
Header ("content-Type: text/html; charset = UTF-8 ");
Set_time_limit (120 );
$ Host = isset ($ _ POST ['url'])? Chop (str_replace ('HTTP: // ', '', $ _ POST ['url']): 'www .baidu.com ';
$ Port = isset ($ _ POST ['duankou'])? Chop ($ _ POST ['duankou']): '80 ';
$ Num = 10;
Function microtime_float ()
{
List ($ usec, $ sec) = explode ("", microtime ());
Return (float) $ usec + (float) $ sec );
}
Function getsoft ($ host, $ port)
{
$ Fp = @ fsockopen ($ host, $ port, & $ errno, & $ errstr, 3 );
If (! $ Fp) return 'unknown ';
$ Get = "GET/HTTP/1.1 \ r \ nHost:". $ host. "\ r \ nConnection: Close \ r \ n ";
@ Fputs ($ fp, $ get );
$ Data = '';
While ($ fp &&! Feof ($ fp ))
$ Data. = fread ($ fp, 1024 );
@ Fclose ($ fp );
$ Array = explode ("\ n", $ data );
$ K = 2;
For ($ I = 0; $ I <20; $ I ++)
{
If (stristr ($ array [$ I], 'server') {$ k = $ I; break ;}
}
If (! Stristr ($ array [$ k], 'server') return 'unknown ';
Else return str_replace ('server', 'server soft', $ array [$ k]);
}
Function ping ($ host, $ port)
{
$ Time_start = microtime_float ();
$ Ip = gethostbyname ($ host );
$ Fp = @ fsockopen ($ host, $ port, & $ errno, & $ errstr, 1 );
If (! $ Fp) return 'request timed out. '. "\ r \ n ";
$ Get = "GET/HTTP/1.1 \ r \ nHost:". $ host. "\ r \ nConnection: Close \ r \ n ";
@ Fputs ($ fp, $ get );
@ Fclose ($ fp );
$ Time_end = microtime_float ();
$ Time = $ time_end-$ time_start;
$ Time = ceil ($ time * 1000 );
Return 'reply from '. $ ip.': time = '. $ time. 'ms ';
}
If (isset ($ _ POST ['url']) & isset ($ _ POST ['duankou'])
{
Echo '<font color = "# FF0000">'. getsoft ($ host, $ port). '</font> ';
Echo 'pinging '. $ host. '['. gethostbyname ($ host ). '] with Port :'. $ port. 'of data :'. "\ r \ n ";
Ob_flush ();
Flush ();
For ($ I = 0; $ I <$ num; $ I ++)
{
Echo ping ($ host, $ port );
Ob_flush ();
Flush ();
Sleep (1 );
}
}
?>
<Form method = "POST">
Domain name/IP: <input type = "text" name = "url" value = "<? Php echo $ host;?> "Size =" 50 ">
Port: <input type = "text" name = "duankou" value = "<? Php echo $ port;?> "Size =" 10 ">
<Input type = "submit" value = "ping">
</Form>
I hope this article will help you with PHP programming.