<?php
/*
* PHP+socket编程 发送http请求
* 要求能 模拟下载,注册,登陆,批量发帖
*
*/
//http请求类的接口
interface proto {
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Http implements Proto {
const CRLF = "\r\n";
protected $errno = -1;
protected $errstr= '';
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->setHeader('Host: ' . $this->url['host']);
}
//此方法负责写请求行
protected function setLine($method)
{
$this->line[0] = $method . ' ' . $this->url['path'] . ' ' . $this->version;
}
//此方法负责写头信息
protected function setHeader($headline)
{
$this->header[] = $headline;
}
//此方法负责写主体信息
protected function setBody()
{
}
//连接url
public function conn($url){
$this->url = parse_url($url);
//判断端口
if(!isset($this->url['port'])){
$this->url['port'] = 80;
}
$this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,3);
}
//构造get查询数据
function get(){
$this->setLine('GET');
$this->request();
return $this->request();
}
//构造post查询的数据
public function post(){
}
//真正请求
public function request(){
//把请求行、头信息、实体信息,放入一个数组,便于拼接
$req = array_merge($this->line,$this->header,array(''),$this->body,array(''));
//print_r($req);
$req = implode(self::CRLF,$req);
//echo $req;
fwrite($this->fh, $req);
while(!feof($this->fh)){
$this->response .= fread($this->fh, 1024);
}
$this->close();//关闭连接
return $this->response;
}
//关闭连接
public function close(){}
}
$url = 'http://news.XX.com/14/0505/02/9RESIA7T00014AED.html';
$http = new Http($url);
echo $http->get();
//echo $http->request();
?>
PHP socket编程案例,参照视频教程
最新推荐文章于 2022-07-29 22:28:01 发布