使用PHP Socket 编程模拟Http post和get请求


Posted in PHP onNovember 25, 2014

这里给大家分享一段使用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);

?>
PHP 相关文章推荐
实现分十页分向前十页向后十页的处理
Oct 09 PHP
在IIS上安装PHP4.0正式版
Oct 09 PHP
php INI配置文件的解析实现分析
Jan 04 PHP
Warning: session_destroy() : Trying to destroy uninitialized sessionq错误
Jun 16 PHP
基于php冒泡排序算法的深入理解
Jun 09 PHP
php根据身份证号码计算年龄的实例代码
Jan 18 PHP
Php中使用Select 查询语句的实例
Feb 19 PHP
ThinkPHP中I(),U(),$this-&gt;post()等函数用法
Nov 22 PHP
ZendFramework框架实现连接两个或多个数据库的方法
Dec 08 PHP
PHP yield关键字功能与用法分析
Jan 03 PHP
微信JSSDK分享功能图文实例详解
Apr 08 PHP
不常用但很实用的PHP预定义变量分析
Jun 25 PHP
PHP实现无限极分类图文教程
Nov 25 #PHP
php获取指定日期之间的各个周和月的起止时间
Nov 24 #PHP
Thinkphp搭建包括JS多语言的多语言项目实现方法
Nov 24 #PHP
thinkphp判断访客为手机端或PC端的方法
Nov 24 #PHP
ThinkPHP公共配置文件与各自项目中配置文件组合的方法
Nov 24 #PHP
php使用str_replace实现输入框回车替换br的方法
Nov 24 #PHP
thinkphp循环结构用法实例
Nov 24 #PHP
You might like
destoon安全设置中需要设置可写权限的目录及文件
2014/06/21 PHP
ThinkPHP 3使用OSS的方法
2018/07/19 PHP
PHP析构函数destruct与垃圾回收机制的讲解
2019/03/22 PHP
laravel实现Auth认证,登录、注册后的页面回跳方法
2019/09/30 PHP
php获取是星期几的的一些常用姿势
2019/12/15 PHP
PHPStorm2020.1永久激活及下载更新至2020(推荐)
2020/09/25 PHP
jQuery 白痴级入门教程
2009/11/11 Javascript
图片延迟加载的实现代码(模仿懒惰)
2013/03/29 Javascript
input 输入框获得/失去焦点时隐藏/显示文字(jquery版)
2013/04/02 Javascript
教你如何在 Javascript 文件里使用 .Net MVC Razor 语法
2014/07/23 Javascript
详细解读JavaScript编程中的Promise使用
2015/07/27 Javascript
基于Bootstrap的后台管理面板 Bootstrap Metro Dashboard
2016/06/17 Javascript
JavaScript 程序错误Cannot use 'in' operator to search的解决方法
2017/07/10 Javascript
使用vs code开发Nodejs程序的使用方法
2017/09/21 NodeJs
jQuery动态添加元素无法触发绑定事件的解决方法分析
2018/01/02 jQuery
详解babel升级到7.X采坑总结
2019/05/12 Javascript
Vue 开发必须知道的36个技巧(小结)
2019/10/09 Javascript
js实现搜索提示框效果
2020/09/05 Javascript
利用Fn.py库在Python中进行函数式编程
2015/04/22 Python
python微信公众号之关注公众号自动回复
2018/10/25 Python
python利用多种方式来统计词频(单词个数)
2019/05/27 Python
OpenCV 边缘检测
2019/07/10 Python
Win10 安装PyCharm2019.1.1(图文教程)
2019/09/29 Python
Pytorch使用MNIST数据集实现基础GAN和DCGAN详解
2020/01/10 Python
详解PyQt5信号与槽的几种高级玩法
2020/03/24 Python
python自动化发送邮件实例讲解
2021/01/04 Python
LN-CC日本:高端男装和女装的奢侈时尚目的地
2019/09/01 全球购物
项目开发计划书
2014/01/09 职场文书
收银员的岗位职责范本
2014/02/04 职场文书
2014年迎新年活动方案
2014/02/19 职场文书
勤奋学习演讲稿
2014/05/10 职场文书
服务标语大全
2014/06/18 职场文书
开会通知
2015/04/20 职场文书
国家助学贷款承诺书
2015/04/30 职场文书
Java内存模型之happens-before概念详解
2021/06/13 Java/Android
Redis安装使用RedisJSON模块的方法
2022/03/23 Redis