存档

文章标签 ‘fsockopen’

最近一直在写淘宝客的程序,因为网络的原因,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 = [...]

五 1st, 2010 | Filed under PHP
标签: , ,