标签归档:fsockopen

myhttp类 php使用fsockopen实现稳定的HTTP连接

最近一直在写淘宝客的程序,因为网络的原因,file_get_contents经常读取出错,想到了比较稳定的方法,使用fsockopen连接API。fsockopen 函数在网上介绍的还是很多的,但是介绍再多,创建http请求仍然是一件比较麻烦的。
fsockopen调用的方法比较繁琐,要使用得到的数据还要去掉http头,所以冒出了写一个通用的类的方法。今天正好是51假日,在家写了这种的一个类。

<?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;
?>