php利用socket发请求

来源:互联网 发布:淘宝行业排名 编辑:程序博客网 时间:2024/06/06 13:07
<?php//设置php运行时间set_time_limit(0);interface Item{//链接urlpublic function conn($url);//get请求public function get();//post请求public function post();// 关闭连接    public function close();}class Socket implements Item{const CRLF  = "\r\n";    protected $errno = -1;    protected $error = '';    protected $response = '';    protected $url = null;    protected $version = 'HTTP/1.1';    protected $fh = null;    protected $line = array();    protected $header = array();    protected $body = array();public function __construct($url){$this -> conn($url);$this -> header('Host: ' . $this->url['host']);}//链接urlpublic function conn($url){//分析url$this -> url = parse_url($url);//看看有没有其他的端口号if(!isset($this-> url['port'])){$this-> url['port'] = 80;}$fh = $this -> url;$this -> fh = fsockopen($fh['host'],$fh['port'],$this->errno,$this->error,5);}//写头信息public function header($header){$this -> header[] = $header;}//写请求行信息public function line($method){$this -> line[0] = $method . ' ' . $this->url['path'] . ' '. $this-> version;}//请求主体信息public function body($body){$this -> body[] = http_build_query($body);}//构造get请求public function get(){//行信息$this -> line('GET');//读写操作$this -> request();//返回页面return $this -> response;}//post请求public function post($body = []){//行信息$this -> line('POST');//设置表单提交的数据格式$this -> header('Content-type: application/x-www-form-urlencoded');//设置提交的主体信息$this -> body($body);//计算主体提交的长度$this -> header('Content-length: '. strlen($this -> body[0]));//读写操作$this -> request();}//真正的请求public function request(){//把请求行 请求头 主体信息 拼起来放置到一个数组中,便于操作$res = array_merge($this -> line , $this -> header , [''] , $this -> body , [''] );//进行数组分割$res = implode(self::CRLF,$res);//进行文件写入fwrite($this -> fh , $res);//进行读文件while(!feof($this -> fh)){$this -> response .= fread($this -> fh , 2048);}//关闭连接$this -> close();}//进行资源关闭public function close(){fclose($this -> fh);}}/*get请求*/$url = 'http://www.zixue.it/thread-10101-1-1.html';$socket = new Socket($url);echo $socket -> get();/*post请求*/ $url = 'http://127.0.0.1/http/01.php';$name = 'ad;dd;f';$pwd  = 'hhe';$socket = new Socket($url);$data = ['name'=>$name,'pwd'=>$pwd];$socket -> post($data);

0 0
原创粉丝点击