This example describes the ping port function of the PHP implementation. Share to everyone for your reference.
The specific implementation code is as follows:
Copy Code code as follows:
<?php
/*
* @author Xujiajay
* @date 2010-10-7
* @function PHP functions that can ping ports
*
*/
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 to ' unknown ';
$get = "Get/http/1.1\r\nhost:" $host. " \r\nconnection:close\r\n\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 < $i + +)
{
if (Stristr ($array [$i], ' Server ') {$k = $i; break;}
}
if (!stristr ($array [$k], ' Server ') return to ' unknown ';
else return Str_replace (' Servers ', ' Server Software ', $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\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=" >
Port: <input type= "text" name= "Duankou" value= "<?php echo $port;? > "Size=" >
<input type= "Submit" value= "ping" >
</form>
I hope this article will help you with your PHP program design.