使用PHP Socket 编程模拟Http post和get请求
这里给大家分享一段使用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 /**
* 使用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);
?>
使用PHP Socket 编程模拟Http post和get请求的更多相关文章
- socket编程模拟linux下的ssh代码实现
实现思路: 1.提供输入指令的客户端: 2.提供返回执行指令结果的服务端 3.寻找服务端返回结果一次无法全部接收的解决思路 服务端代码(ssh_server.py) #coding=utf-8 imp ...
- HTTP 笔记与总结(5)socket 编程:使用 HTTP 协议模拟登录并发帖
在 VeryCD 上注册两个帐号,发送和接收站内信,观察 POST 请求时发送的参数(h****2 发送给 d***2).(最好用 FireFox 的 FireBug 工具,发送站内信之前选中 “保持 ...
- Socket编程之聊天程序 - 模拟Fins/ModBus协议通信过程
设备控制软件编程涉及到的基本通信方式主要有TCP/IP与串口,用到的数据通信协议有Fins与ModBus. 更高级别的通信如.net中的Remoting与WCF在进行C/S架构软件开发时会采用. 本篇 ...
- python网络编程-socket编程
一.服务端和客户端 BS架构 (腾讯通软件:server+client) CS架构 (web网站) C/S架构与socket的关系: 我们学习socket就是为了完成C/S架构的开发 二.OSI七层 ...
- socket编程基础
socket编程 什么是socket 定义 socket通常也称作套接字,用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过套接字向网络发出请求或者应答网络请求. socket起源于Unix ...
- HTTP 笔记与总结(4 )socket 编程:批量发帖
浏览器发送 POST 请求: 表单 form.html <!doctype html> <html lang="en"> <head> < ...
- HTTP 笔记与总结(3 )socket 编程:发送 GET 请求
使用 PHP + socket 模拟发送 HTTP GET 请求,过程是: ① 打开连接 ② 构造 GET 请求的数据:写入请求行.请求头信息.请求主体信息(GET 请求没有主体信息) ③ 发送 GE ...
- 8.1 Socket编程
8.1 Socket编程 在很多底层网络应用开发者的眼里一切编程都是Socket,话虽然有点夸张,但却也几乎如此了,现在的网络编程几乎都是用Socket来编程.你想过这些情景么?我们每天打开浏览器浏览 ...
- <转>Go语言TCP Socket编程
授权转载: Tony Bai 原文连接: https://tonybai.com/2015/11/17/tcp-programming-in-golang/ Golang的主要 设计目标之一就是面向大 ...
随机推荐
- sql存储过程——名称 ****不是有效的标识符
转载自http://blog.csdn.net/xb12369/article/details/8202703 假设存储过程:proc_test create proc proc_test @Prod ...
- 安装appuim
一.作为一名软件测试人员,对工作习惯和品质的有要求,要有对问题的敏感度,遇到问题就不能轻易放过,提前保存一切可能对分析解决问题有帮助的资料,不怕麻烦,尽可能的全面详细,不漏重点.若神经大条,嫌麻烦,不 ...
- call ,apply 和 bind的用法与区别
作用都是一样的,官方解释:"调用一个对象的一个方法,以另一个对象替换当前对象", 简单来说就是改变当前使用该方法的对象中的this指向: var xw = { name : &qu ...
- JPA 系列教程10-双向一对一关联表
双向一对一关联表的ddl语句 CREATE TABLE `t_person` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255 ...
- SELinux Policy Macros
参考:http://selinuxproject.org/page/NB_RefPolicy Directory Macros macro expansion getattr_dir_perms ge ...
- mybatis结合redis实战二级缓存(六)
之前的文章中我们意见分析了一级缓存.二级缓存的相关源码和基本原理,今天我们来分享下了mybatis二级缓存和redis的结合,当然mybatis二级缓存也可以和ehcache.memcache.OSC ...
- Windows进程间通信(中)
二.文件映射 文件映射(Memory-Mapped Files)能使进程把文件内容当作进程地址区间一块内存那样来对待.因此,进程不必使用文件I/O操作,只需简单的指针操作就可读取和修改文件的内容. W ...
- WIN2003 设置 OPENVPN 服务端
服务器端 安装openvpn 在这里http://swupdate.openvpn.org/community/releases/openvpn-install-2.3.4-I004-i686.exe ...
- javascript 如何正确使用getElementById,getElementsByName(), and getElementsByTagName()
WEB标准下可以通过getElementById(), getElementsByName(), and getElementsByTagName()访问DOCUMENT中的任一个标签. (1)get ...
- Entity Framework技巧系列之七 - Tip 26 – 28
提示26. 怎样避免使用不完整(Stub)实体进行数据库查询 什么是不完整(Stub)实体? 不完整实体是一个部分填充实体,用于替代真实的对象. 例如: 1 Category c = new Cate ...