php socket类
2015-06-12 14:15
381 查看
class socketClass{ private $host; private $url; private $error_no = 0; public $error_str = ''; private $port = 80; private $timeout = 5; private $method; private $param; private $fp; private $content = ''; private $header = array(); public function __construct($host, $port, $url, $param, $method='GET', $timeout=5) { $this->host = $host; $this->port = $port; $this->url = $url; $this->timeout = $timeout; $this->method = $method; if(is_array($param)){ $this->param = http_build_query($param); }else{ $this->param = $param; } } private function connect(){ $this->fp = fsockopen($this->host, $this->port, $this->error_no, $this->error_str, $this->timeout); if(!$this->fp){ $this->error_str = 'socket connect failed'; return false; } return true; } private function send(){ $this->fp = ''; if(!$this->connect()){ $this->error_str = 'connect socket failed'; return false; } if($this->method == 'POST'){ $header = "POST $this->url HTTP/1.1\r\n"; }else{ if(!empty($this->param)){ $header = "GET $this->url?$this->param HTTP/1.1\r\n"; }else{ $header = "GET $this->url HTTP/1.1\r\n"; } } $header .= "Content-Length:" . strlen($this->param) . "\r\n"; $header .= "Host:$this->host:$this->port\r\n"; $header .= "Content-Type:application/x-www-form-urlencode\r\n"; $header .= "Connection:close\r\n\r\n"; if($this->method == 'POST'){ $header .= "$this->param\r\n\r\n"; } if(!empty($this->header)){ foreach ($this->header as $key=>$val){ $tmep = urlencode($val); $header .= "$key:$temp\r\n"; } } fwrite($this->fp, $header); while(!feof($this->fp)){ $this->content .= fread($this->fp, 1024); } fclose($this->fp); return true; } public function getContent(){ if(!$this->send()){ return false; } $pos = strpos($this->content, "\r\n\r\n"); $this->content = substr($this->content, $pos); return $this->content; } public function setHeader($key, $val){ $this->header[$key] = $val; } public function getErrorStr(){ return $this->error_str; } } $host = 'localhost'; $port = 81; $url = 'http://localhost/phpdemo/php/socket_accept.php'; $param = array('username'=>'beggar', 'passwd'=>'20060400'); $method = 'GET'; $timeout = 10; $http = new socketClass($host, $port, $url, $param, $method, $timeout); $http->setHeader('referer', $url); $http->setHeader('Accept', '*/*'); $header = $http->getContent(); echo $header;
相关文章推荐
- PHP 的DataGrid 分页
- PHP的JSON处理方式,
- 为什么PHP能够受到大家追捧和喜爱,又为什么饱受嘲讽?
- 用二十秒记住几个PHP基础知识点
- sublime phpcs
- php curl
- PHP安装,报错信息和解决过程
- TP-Link路由器端口映射8081端口的Nexus服务外网无法访问的解决办法
- PHP中读取大文件实现方法详解
- Yii学习笔记之六(HTML生成帮助类api 翻译)
- laravel5学习笔记(3)——复杂的路由
- php结合ACCESS的跨库查询功能
- Response.getWriter() 和Response.getOutputStream冲突
- (转)解析PHP中ob_start()函数的用法
- FragmentPagerAdapter与FragmentStatePagerAdapter区别
- LAMP环境搭建3-PHP5.6
- php 开发环境图文配置
- Windows下PHPUnit安装
- 【AS400系列】通过程序例子说明检查AS400用户密码的API-QSYGETPH
- (转)ThinkPHP系统常量