欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-10 21:37:16
这里给大家分享一段使用php socket 编程模拟http post和get请求的代码,非常的实用,结尾部分我们再讨论下php模拟http请求的几种方法。 复制代码 代...

这里给大家分享一段使用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参数形式为""
         * 不能够带"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 = 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 = "=" . $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可以到这里下载:

复制代码 代码如下:

<?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);
?>