网上找到一个用fsockopen函数实现http请求的类,感觉不错。
<?php
/*
CatSeven myHttp Vesion 0.1
======CopyRight======
Home:http://www.myw3.cn/myDevise/myHttp/
Design:Miao Qiyuan[miaoqiyuan.cn]
Downloads:http://downloads.myw3.cn/file=myDevise/myHttp/0.1
*/
class myHttp{
public $Method,$URI,$SendDate;
public $HttpServerPort,$HttpServer,$HttpServerIP;
public $Err,$ErrStr;
public $timeout;
public $responseText;
public function __construct($uri='/',$method='get',$query='',$server='localhost',$port='80',$serverip='',$timeout=30){
$this->URI=$uri;
$this->Method=$method;
$this->SendDate=$query;
$this->HttpServer=$server;
$this->HttpServerPort=$port;
$this->HttpServerIP=$serverip;
if(is_numeric($timeout))$this->timeout=$timeout;
}
public function send(){
$this->Method=strtoupper($this->Method);
if($this->HttpServerIP=="")$this->HttpServerIP = $this->HttpServer;
if($this->Method=="GET" && strstr($this->URI,"?")==0)$this->URI=$this->URI."?".$this->SendDate;
$sock = fsockopen($this->HttpServerIP,$this->HttpServerPort,$errno,$errstr,$this->timeout);
if(!$sock){
$this->ErrStr=$errstr;
$this->Err=$errno;
die("无法打开".$this->HttpServerIP.":".$this->HttpServerPort);
}
fwrite($sock, $this->Method." ".$this->URI." HTTP/1.0\r\n");
fwrite($sock, "Host: ".$this->HttpServer."\r\n");
if($this->Method=="POST"){
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: ".strlen($this->SendDate) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $this->SendDate."\r\n");
fwrite($sock, "\r\n");
fwrite($sock, "Referer: http://www.myw3.cn/myDevise/myHttp/");
}
fwrite($sock, "Connection: Close\r\n\r\n");
$headers = "";
while ($str = trim(fgets($sock,4096)))
$headers .= "$str\n";
$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);
fclose($sock);
$this->responseText=$body;
}
}
?>
输入参数的方法有两种,在创建类的时候同时输入参数和先创建类,慢慢输入参数。相关例子分别为test,test2,该类同时支持get,post的方法。
<?php
include("myHttp.class.php");
$test = new myHttp();
$test -> URI = "/index.php";
$test -> HttpServer = "www.miaoqiyuan.cn";
$test -> Method = "post";
$test -> SendDate ="s=myhttp";
$test -> send();
echo $test -> responseText;
$test2 = new myHttp('/index.php','get','s=myhttp','www.miaoqiyuan.cn','80','',30);
$test2 -> send();
echo $test2 -> responseText;
?>