続:fsockopen、読み返しデータはfeof関数を採用しにくい

2964 ワード

別の方法でデータを読みます.

<?php 
function httpPost($host,$url,$data,$p)
{
	$conn = fsockopen($host,80,$errno, $errstr, 30);
	if (!$conn) 
	{
		echo "$errstr ($errno)<br />
"; return; } $header = "POST ".$url." HTTP/1.1\r
"; $header.= "Host : {$host}\r
"; $header.= "Content-type: application/x-www-form-urlencoded\r
"; $header.= "Content-Length:".strlen($data)."\r
"; $header.= "Connection: Keep-Alive\r
\r
"; $header.= "{$data}\r
\r
"; fwrite($conn,$header); // $resp=''; $start = microtime(true); /* * echo " <br>"; while (!feof($conn)) { echo " :".(microtime(true)-$start)."<br>"; $resp .= fread($conn,64); echo " :".(microtime(true)-$start)."<br>"; } */ $len=-1; // , , echo " head<br>"; while( ($line=trim(fgets($conn))) != "" ) { echo "head :".(microtime(true)-$start)."<br>"; $header.=$line; if(strstr($line,"Content-Length:")) { list($cl,$len)=explode(" ",$line); } echo "head :".(microtime(true)-$start)."<br>"; } echo " body:".(microtime(true)-$start)."<br>"; $body=fread($conn,$len); echo " :".$body."<br>"; echo " :".(microtime(true)-$start)."<br>"; fclose($conn); echo " :".(microtime(true)-$start)."<br>"; return $resp; } httpPost("127.0.0.1","/aa.php","test",true); ?>

結果:

   head
head   :0.00082898139953613
head   :0.00084185600280762
head   :0.00084590911865234
head   :0.00084781646728516
head   :0.00085091590881348
head   :0.00085282325744629
head   :0.00085592269897461
head   :0.00085783004760742
head   :0.00085997581481934
head   :0.00086688995361328
head   :0.0008699893951416
head   :0.00087189674377441
head   :0.00087499618530273
head   :0.00087690353393555
head   :0.00088000297546387
head   :0.00088191032409668
   body:0.00088381767272949
  :hello
     :0.00088787078857422
  :0.0009307861328125

プロセス全体が速い.
2つの関数と時間を見渡すとfeof判断が終わりバグがあると思います.SOCKを読むことをお勧めします.まずプロトコルヘッダのContent-Longthを取り、Content-Longthで指定した長さでコンテンツを読みます.
討論を歓迎する.