使用PHP Socket 编程模拟Http post和get请求
作者:hebedich 发布时间:2023-11-15 10:58:52
这里给大家分享一段使用PHP Socket 编程模拟Http post和get请求的代码,非常的实用,结尾部分我们再讨论下php模拟http请求的几种方法。
<?php /**
* 使用PHP Socket 编程模拟Http post和get请求
* @author koma
*/ class Http{
private $sp = "\r\n"; //这里必须要写成双引号 private $protocol = 'HTTP/1.1';
private $requestLine = "";
private $requestHeader = "";
private $requestBody = "";
private $requestInfo = "";
private $fp = null;
private $urlinfo = null;
private $header = array();
private $body = "";
private $responseInfo = "";
private static $http = null; //Http对象单例
private function __construct() {}
public static function create() {
if ( self::$http === null ) {
self::$http = new Http();
}
return self::$http;
}
public function init($url) {
$this->parseurl($url);
$this->header['Host'] = $this->urlinfo['host'];
return $this;
}
public function get($header = array()) {
$this->header = array_merge($this->header, $header);
return $this->request('GET');
}
public function post($header = array(), $body = array()) {
$this->header = array_merge($this->header, $header);
if ( !empty($body) ) {
$this->body = http_build_query($body);
$this->header['Content-Type'] = 'application/x-www-form-urlencoded';
$this->header['Content-Length'] = strlen($this->body);
}
return $this->request('POST');
}
private function request($method) {
$header = "";
$this->requestLine = $method.' '.$this->urlinfo['path'].'?'.$this->urlinfo['query'].' '.$this->protocol;
foreach ( $this->header as $key => $value ) {
$header .= $header == "" ? $key.':'.$value : $this->sp.$key.':'.$value;
}
$this->requestHeader = $header.$this->sp.$this->sp;
$this->requestInfo = $this->requestLine.$this->sp.$this->requestHeader;
if ( $this->body != "" ) {
$this->requestInfo .= $this->body;
}
/*
* 注意:这里的fsockopen中的url参数形式为"www.xxx.com"
* 不能够带"http://"这种
*/
$port = isset($this->urlinfo['port']) ? isset($this->urlinfo['port']) : '80';
$this->fp = fsockopen($this->urlinfo['host'], $port, $errno, $errstr);
if ( !$this->fp ) {
echo $errstr.'('.$errno.')';
return false;
}
if ( fwrite($this->fp, $this->requestInfo) ) {
$str = "";
while ( !feof($this->fp) ) {
$str .= fread($this->fp, 1024);
}
$this->responseInfo = $str;
}
fclose($this->fp);
return $this->responseInfo;
}
private function parseurl($url) {
$this->urlinfo = parse_url($url);
}
} // $url = "http://news.163.com/14/1102/01/AA0PFA7Q00014AED.html";
$url = "http://localhost/httppro/post.php"; $http = Http::create()->init($url); /* 发送get请求
echo $http->get(array(
'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
));
*/
/* 发送post请求 */ echo $http->post(array(
'User-Agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
), array('username'=>'发一个中文', 'age'=>22));
php 模拟 http请求
方法一:利用php的socket编程来直接给接口发送数据来模拟post的操作。
建立两个文件post.php,getpost.php
post.php内容如下:
<?php
$flag = 0;
$params = '';
$errno = '';
$errstr = '';
//要post的数据
$argv = array(
'var1'=>'abc',
'var2'=>'how are you , my friend??');
//构造要post的字符串
foreach ($argv as $key=>$value) {
if ($flag!=0) {
$params .= "&";
$flag = 1;
}
$params.= $key."="; $params.= urlencode($value);
$flag = 1;
}
$length = strlen($params);
//创建socket连接
$fp = fsockopen("localhost",81,$errno,$errstr,10) or exit($errstr."--->".$errno);
//构造post请求的头
$header = "POST /flandy/getpost.php HTTP/1.1\r\n";
$header .= "Host:127.0.0.1\r\n";
$header .= "Referer:/flandy/post.php\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".$length."\r\n";
$header .= "Connection: Close\r\n\r\n";
//添加post的字符串
$header .= $params."\r\n";
//发送post的数据
fputs($fp,$header);
$inheader = 1;
while (!feof($fp)) {
$line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
if ($inheader && ($line == "\n" || $line == "\r\n")) {
$inheader = 0;
}
if ($inheader == 0) {
echo $line;
}
}
fclose($fp);
?>
getpost.php的内容如下
<?php
echo "this is the data posted";
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
?>
结果输出:
this is the data postedArray
(
[var1] => abc
[var2] => how are you , my friend??
)
以上代码在本机81端口下已经通过测试。
方法二:
使用PHP的curl扩展或HttpClient.class.php类,这两个非常类似,下面简单的列出curl的实现代码。
两个文件post2.php和getpost2.php
post2.php的内容如下:
<?php
$psecode = 'NDE005';
$website = 'www.baidu.com';
$amt = 1;
$pwd = 123456;
$ch = curl_init();
$curl_url = "http://localhost:81/flandy/getpost2.php?web=" . $website .
"&pwd=" . $pwd . "&action=check&pseid=" . $psecode .
"&amt=" . $amt;
curl_setopt($ch, CURLOPT_URL, $curl_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不直接输出,返回到变量
$curl_result = curl_exec($ch);
$result = explode(',', $curl_result);
curl_close($ch);
print_r($result);
?>
getpost2.php的内容如下:
<?php
echo "returndata<br>";
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
?>
结果输出:
Array ( [0] => returndataArray
(
[web] => 'wwwbaiducom'
[pwd] => 123456
[action] => check
[pseid] => 'NDE005'
[amt] => 1
)
)
方法三:
这个要借助第三方类库HttpClient可以到这里下载:http://scripts.incutio.com/httpclient/
<?php
require_once 'HttpClient.class.php';
$params = array('web' => 'www.baidu.com',
'pwd' => '123456',
'action' => 'check',
'pseid' => 'NDE005',
'amt' => 1);
$pageContents = HttpClient::quickPost('http://localhost:81/flandy/getpost3.php', $params);
$result = explode(',', $pageContents);
print_r($result);
?>
猜你喜欢
- 如果你是个赛车手,并且按一下按钮就能够立即更换引擎而不需要把车开到车库里去换,那会是什么感觉呢?MySQL数据库为开发人员所做的就好像是按按
- goto语句在Go编程语言中的goto语句提供无条件跳转从跳转到标记声明的功能。注意:使用goto语句是高度劝阻的在任何编程语言,因为它使得
- 小编语:小编我最早使用的网页制作工作就是FrontPage啦,FrongPage方便简单,会用Word就能做网页。如果你对网页制作要求不高,
- 这是我的第一个真正意思上的自动化脚本。1、练习的测试用例为:打开百度首页,搜索“胡歌”,然后检索列表,有无“胡歌的新浪微博”这个链接 2、在
- 有很多应用项目, 刚起步的时候用MYSQL数据库基本上能实现各种功能需求,随着应用用户的增多,数据量的增加,MYSQL渐渐地出现不堪重负的情
- 备注:Ken Henderson 从开发者的角度来阐述了SQL SERVER 2000内存管理的内部机制简介在本专栏中,我们将从一个开发者的
- 如果你只使用一个更新日志,你只须清空日志文件,然后移走旧的更新日志文件到一个备份中,然后启用新的更新日志。用下列方法可以强制服务器启用新的更
- * 前,我在公司做设计,当时就已经做到技术总监,Photoshop是自学的,当时觉得全世界比我Photoshop强的人也不在多数。七年前,
- javascript 代码实现vbscript中的trim、left、right等函数兼容IE,FireFox。<style>b
- JS获取网页中HTML元素的几种方法分析:getElementById getElementsByName getElementsByTag
- ABS(x) 函数,此函数用来返回一个数的绝对值。 ACOS(x)函数,返回X的反余弦值。X范围从1到-1,输入值从0到派,以弧度为单位。
- 我们前期开发了一个只有公司客服人员才能使用的系统——有限的几个客服人员。就是这有限的几个客服人员前几天突然就提出这样的问题:我们每隔很短一段
- JavaScript 中的并没有提供像 VBScript 里的 DateAdd 方法用于日
- 这篇文章主要介绍了Python hashlib常见摘要算法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,
- login.html <script language = "javascript" type = "t
- jQuery的makeArray有其局限性(1.3.4还有bug),我自己实现了一个,不过涉及N多辅助方法。var dom = {},_to
- 1、fastcgi ,通过flup模块来支持,在nginx里对应的配置指令是 fastcgi_pass2、http,nginx使用proxy
- 按照惯例,年底的淘宝的确是到了“需要改版的时候”。这次新版的淘宝首页上线,乍看并没有多少夺人眼球的地方,但仔细揣摩其中的细节,还是发现了不少
- 1,exists和in的理解exists:如果子查询中包括某一行,那么就为TRUE in:如果操作数为TRUE等于表达式列表中的一个,那么就
- 废话不多说了,直接给大家贴代码了,具体代码如下所示:// ----ajax begin $.ajax({type: "