深入解析fsockopen与pfsockopen的区别

作者:美狮美高梅官方网站

 fwrite($conn,$header);

2. 使用 PHP 向页面 POST 数据 复制代码 代码如下:
function socketPost($url, $data, &$ret)
{
 $urlArr = parse_url($url);
 $host = $urlArr['host'];
 $port = isset($urlArr['port'])?$urlArr['port']:80;
 $path = isset($urlArr['path'])?$urlArr['path']:"/";
 $fp = fsockopen($host, $port, $errno, $errstr, 30);
 if (!$fp)
 {
     echo "$errstr ($errno)
n";
美狮美高梅官方网站 ,  return false;
 }
 else
 {
新美高梅网站 ,     $out = "POST $path HTTP/1.1rn";
     $out .= "Host: $hostrn";
  $out .= "Content-Type: application/x-www-form-urlencodedrn";
  $out .= "Content-Length: ".strlen($data)."rn";
     $out .= "Connection: Keep-Alivernrn";
  $out .= $data;
  $ret = "";
     fwrite($fp, $out);
     while (!feof($fp))
  {
         $ret .= fgets($fp, 128);
     }
     fclose($fp);
 }
 return true;
}
?>

";;
}
$endTime = microtime(true);
 echo ($pffirst?"pfsocket":"fsocket").":".($middleTime-$startTime);
 echo "
";
 echo ($pffirst?"fsocket":"pfsocket").":".($endTime-$middleTime);

如果post报错,把$out .= "Connection: Keep-Alivernrn";中的Keep-Alive改成Close

";

1. 使用 PHP 获得网页内容 GET方式 复制代码 代码如下:
function socketGet($url, &$ret)
{
 $urlArr = parse_url($url);
 $host = $urlArr['host'];
 $port = isset($urlArr['port'])?$urlArr['port']:80;
 $path = isset($urlArr['path'])?$urlArr['path']:"/";
 $fp = fsockopen($host, $port, $errno, $errstr, 30);
 if (!$fp)
 {
  echo "$errstr ($errno)
n";
  return false;
 }
 else
 {
     $out = "GET $path HTTP/1.1rn";
     $out .= "Host: $hostrn";
     $out .= "Connection: Closernrn";
  $ret = "";
     fwrite($fp, $out);
     while (!feof($fp))
  {
         $ret .= fgets($fp, 128);
     }
     fclose($fp);
 }
 return true;
}
?>


 $header = "POST ".$url." HTTP/1.1rn";
 $header.= "Host : {$host}rn";
 $header.= "Content-type: application/x-www-form-urlencodedrn";
 $header.= "Content-Length:".strlen($data)."rn";
 $header.= "Connection: Keep-Alivernrn"; 
 $header.= "{$data}rnrn";

 $conn = $func($host,80,$errno, $errstr, 30);
 if (!$conn)
 {
  echo "$errstr ($errno)
n";
  return;
 }

按手册上说,这两个函数的唯一区别是,pfsockopen是持续连接,而fsockopen不是.
我写了个代码了一下: 复制代码 代码如下:
$data="1,0,721,73,1,0,0,43290000,0,60D81D509BC00451,3,FFFFFFFF";
//
$host = '127.0.0.1';
$url = "/aa.php";
$pffirst = false;
$times = 1000;
$startTime = microtime(true);
for ($index = 0; $index < $times; $index++) {
 echo httpPost($host,$url,$data,$pffirst)."

本文由美狮美高梅官方网站发布,转载请注明来源

关键词: