PHP socket 模拟POST 请求实例代码


Posted in PHP onJuly 18, 2016

我们用到最多的模拟POST请求几乎都是使用php curl来实现了,没考虑到PHP socket也可以实现,今天看到朋友写了一文章,下面我来给大家分享一下PHP socket模拟POST请求实例。

以前模拟post请求俺都用PHP curl扩展实现来着,没想过PHP socket也可以实现。最近翻了下相关资料才发现原来没有那么高深,只是以前一直没有完全理解post的原理和本质而已,其实就是发送给目的程序一个标志为post的协议串如下:

POST /目的程序url HTTP/1.1

Accept: 接收信息格式

Referer: url来路

Accept-Language: 接收语言

Content-Type: application/x-www-form-urlencoded

Cookie: 网站cookie,不用俺过多解释,对吧?

User-Agent: 用户代理,操作系统及版本、CPU 类型、浏览器及版本等信息

Host: 要发送到的主机地址

Content-Length: 发送数据的长度

Pragma: 本地是否存在缓存

Cache-Control: 是否需要网页缓存

Connection: 连接状态

username=fengdingbo&password=3water.com   //post发送的数据

我想大家对表单的post方法提交数据应该是最熟悉不过了,例如我们想把用户名和密码发送给某个页面的时候,填写好相应的input框,点击提交按钮,最后把这个表单发送到action程序的就是以上数据。知道了这一点我想就不难了

这时候我们只需要用php的socket打开一个端口,例如80端口,把以上信息利用这个端口发送给目的程序就行了。

我们如何在一个端口上建立一个socket通道呢?

在PHP中是如此简单呢!

官方给的原型:

resource fsockopen ( string $hostname [, int $port = -1 [, int &$errno [, string &$errstr [, float $timeout = ini_get("default_socket_timeout") ]]]] )

下边是人类的理解:

fsockopen(主机名称,端口号,错误号的&变量,错误提示的&变量,超时时间)
主机名称就是你需要发送数据的目的地;
端口号就是这个目的程序会在哪个端口等着你的数据;
错误号的&变量,这个是如果建立socket不成功的时候返回的错误编号;
错误提示的&变量,是错误的时候返回的错误提示信息;
超时时间,就是post数据之后如果对方没有回应信息,等待的最长时间。

如果不出意外(你正确的设置fsockopen()函数的参数)的话,一个socket通道现在已经打开了,我们下一步需要做的就是,通过这个打开的通道把post请求协议发给目的程序,这时候可以使用fwrite或者fputs函数中的任意一个,把post的请求格式发给fsockopen()打开的资源句柄,这时候一个伟大的socket模拟的post请求就诞生了。

 代码如下

<?php
/**
 * SOCKET扩展函数
 * @copyright (c) 2013
 * @author Qiufeng <fengdingbo@gmail.com>
 * @link https://3water.com
 * @version 1.0
 */
 
/**
 * Post Request
 *
 * @param string $url 
 * @param array $data
 * @param string $referer
 * @return array
 */
if ( ! function_exists('socket_post'))
{
 function socket_post($url, $data, $referer='')
 {
 if( ! is_array($data))
 {
 return;
 }
 
 $data = http_build_query($data);
 $url = parse_url($url);
 
 if ( ! isset($url['scheme']) || $url['scheme'] != 'http')
 {
 die('Error: Only HTTP request are supported !');
 }
 
 $host = $url['host'];
 $path = isset($url['path']) ? $url['path'] : '/';
 
 // open a socket connection on port 80 - timeout: 30 sec
 $fp = fsockopen($host, 80, $errno, $errstr, 30);
 
 if ($fp)
 {
 // send the request headers:
 $length = strlen($data);
 $POST = <<<HEADER
POST {$path} HTTP/1.1
Accept: text/plain, text/html
Referer: {$referer}
Accept-Language: zh-CN,zh;q=0.8
Content-Type: application/x-www-form-urlencodem 
Cookie: token=value; pub_cookietime=2592000; pub_sauth1=value; pub_sauth2=value
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17
Host: {$host}
Content-Length: {$length}
Pragma: no-cache
Cache-Control: no-cache
Connection: closern
{$data}
HEADER;
 fwrite($fp, $POST);
 $result = '';
 while(!feof($fp))
 {
 // receive the results of the request
 $result .= fread($fp, 512);
 }
 }
 else
 {
 return array(
  'status' => 'error',
  'error' => "$errstr ($errno)"
  );
 }
 
 // close the socket connection:
 fclose($fp);
 
 // split the result header from the content
 $result = explode("rnrn", $result, 2);
 
 // return as structured array:
 return array(
 'status' => 'ok',
 'header' => isset($result[0]) ? $result[0] : '',
 'content' => isset($result[1]) ? $result[1] : ''
 );
 }
}
 
print_r(socket_post('https://3water.com/', array('name='=>'qiufeng','password'=>md5('3water.com'))));
/* e.g: socket_post('https://3water.com', array('name='=>'qiufeng','password'=>md5('3water.com'))); */
/* End of file socket_helper.php */

实际上,当socket通道打开时,我们传的COOKIE是正确的话,(截图运行的php代码来自上边,运行后返回的网页出现了我的用户名,说明对方网站已经承认我已经登录了)咱就可以干N多事情,比如刷帖,刷回复等,你们懂的,对吧?

好了上面还不够有说服力我们来看一个php socket实现图片上传

这个代码有两点要注意:

一是他是http的post 请求;

二是表单上传协议,

下的请求 串适合任何语言.

代码如下 

<?php 
 
  $remote_server = "3water.com"; 
 
  $boundary = "---------------------".substr(md5(rand(0,32000)),0,10); 
   
  // Build the header 
  $header = "POST /api.php?action=twupload HTTP/1.0rn"; 
  $header .= "Host: {$remote_server}rn"; 
  $header .= "Content-type: multipart/form-data, boundary=$boundaryrn"; 
 
  /* 
  // attach post vars 
  foreach($_POST AS $index => $value){ 
   $data .="--$boundaryrn"; 
   $data .= "Content-Disposition: form-data; name="".$index.""rn"; 
   $data .= "rn".$value."rn"; 
   $data .="--$boundaryrn"; 
  } 
  */
  $file_name = "aaa.jpg"; 
  $content_type = "image/jpg"; 
 
  $data = ''; 
  // and attach the file 
  $data .= "--$boundaryrn"; 
 
  $content_file = file_get_contents('aaa.jpg'); 
  $data .="Content-Disposition: form-data; name="userfile"; filename="$file_name"rn"; 
  $data .= "Content-Type: $content_typernrn"; 
  $data .= "".$content_file."rn"; 
  $data .="--$boundary--rn"; 
 
  $header .= "Content-length: " . strlen($data) . "rnrn"; 
     // Open the connection 
 
 
  $fp = fsockopen($remote_server, 80); 
  // then just 
  fputs($fp, $header.$data); 
  // reader 
 
 while (!feof($fp)) { 
  echo fgets($fp, 128); 
 } 
 
fclose($fp);

希望本文对大家的 PHP程序设计有所帮助。

PHP 相关文章推荐
php下防止单引号,双引号在接受页面转义的设置方法
Sep 25 PHP
php curl获取网页内容(IPV6下超时)的解决办法
Jul 16 PHP
PHP CURL获取cookies模拟登录的方法
Nov 04 PHP
php实现通用的信用卡验证类
Mar 24 PHP
php获取twitter最新消息的方法
Apr 14 PHP
php根据日期显示所在星座的方法
Jul 13 PHP
详解PHP序列化和反序列化原理
Jan 15 PHP
PHP的mysqli_thread_id()函数讲解
Jan 24 PHP
PHP快速排序算法实现的原理及代码详解
Apr 03 PHP
php使用scandir()函数扫描指定目录下所有文件示例
Jun 08 PHP
PHP实现给定一列字符,生成指定长度的所有可能组合示例
Jun 22 PHP
thinkPHP5框架接口写法简单示例
Aug 05 PHP
Yii2简单实现给表单添加验证码的方法
Jul 18 #PHP
yii2缓存Caching基本用法示例
Jul 18 #PHP
yii2.0实现创建简单widgets示例
Jul 18 #PHP
php cookie工作原理与实例详解
Jul 18 #PHP
Yii2针对指定url的生成及图片等的引入方法小结
Jul 18 #PHP
图文详解PHP环境搭建教程
Jul 16 #PHP
Yii调试查看执行SQL语句的方法
Jul 15 #PHP
You might like
ThinkPHP3.2.2的插件控制器功能简述
2014/07/09 PHP
php Imagick获取图片RGB颜色值
2014/07/28 PHP
PHP对称加密算法(DES/AES)类的实现代码
2017/11/14 PHP
ThinkPHP中获取指定日期后工作日的具体日期方法
2018/10/14 PHP
PHP创建文件及写入数据(覆盖写入,追加写入)的方法详解
2019/02/15 PHP
jquery打开直接跳到网页最下面、最低端实现代码
2013/04/22 Javascript
Nodejs全栈框架StrongLoop推荐
2014/11/09 NodeJs
jQuery实现的网页左侧在线客服效果代码
2015/10/23 Javascript
深入剖析JavaScript中的函数currying柯里化
2016/04/29 Javascript
将json转换成struts参数的方法
2016/11/08 Javascript
js实现固定宽高滑动轮播图效果
2017/01/13 Javascript
浅谈JS中的反柯里化( uncurrying)
2017/08/17 Javascript
解读ES6中class关键字
2017/11/20 Javascript
layer弹出的iframe层在执行完毕后关闭当前弹出层的方法
2018/08/17 Javascript
layui 实现表格某一列显示图标
2019/09/19 Javascript
electron踩坑之remote of undefined的解决
2020/10/06 Javascript
[08:42]DOTA2每周TOP10 精彩击杀集锦vol.2
2014/06/25 DOTA
Python中为feedparser设置超时时间避免堵塞
2014/09/28 Python
python查找指定具有相同内容文件的方法
2015/06/28 Python
SQLite3中文编码 Python的实现
2017/01/11 Python
Python设计实现的计算器功能完整实例
2017/08/18 Python
Python使用Matplotlib实现Logos设计代码
2017/12/25 Python
Python实现的HMacMD5加密算法示例
2018/04/03 Python
python使用Matplotlib画条形图
2020/03/25 Python
python剪切视频与合并视频的实现
2020/03/03 Python
Python中zipfile压缩文件模块的基本使用教程
2020/06/14 Python
Python3爬虫中识别图形验证码的实例讲解
2020/07/30 Python
Python join()函数原理及使用方法
2020/11/14 Python
10张动图学会python循环与递归问题
2021/02/06 Python
html5 利用canvas手写签名并保存的实现方法
2018/07/12 HTML / CSS
汽车检测与维修应届毕业生求职信
2013/10/19 职场文书
社区党总支书记先进事迹材料
2014/01/24 职场文书
新闻学专业职业生涯规划范文:我的人生我做主
2014/09/12 职场文书
政风行风评议整改方案
2014/09/15 职场文书
经理助理岗位职责
2015/02/02 职场文书
2016党员发展对象培训心得体会
2016/01/08 职场文书