zoukankan      html  css  js  c++  java
  • 使用PHP得到所有的HTTP请求头_还有应答头

    1)如何获取 客户端请求的头部

    参考网站:

    http://www.neatstudio.com/show-377-1.shtml

    PHP中一般采用getallheaders来获取头部,但事实上,有些模式下是获取不到的(以前真没有注意过在fastcgi下这个函数不能用,当然我现在也没有测试。是老王说的)

    他说:

    在PHP里,想要得到所有的HTTP请求头,可以使用getallheaders方法,不过此方法并不是在任何环境下都存在,比如说,你使用fastcgi方式运行PHP的话,就没有这个方法,所以说我们还需要考虑别的方法,幸运的是$_SERVER里有我们想要的东西,它里面键名以HTTP_开头的就是HTTP请求头:

    $headers = array(); 
    foreach ($_SERVER as $key => $value) { 
        if ('HTTP_' == substr($key, 0, 5)) { 
            $headers[str_replace('_', '-', substr($key, 5))] = $value; 
        } 
    }

    代码很简单,需要说明的是RFC里明确指出了信息头的名字是不区分大小写的。

    2)如果php脚本作为http客户端,用curl去请求远端 服务器,那么如何获取 http响应消息 的应答头!
    代码如下:

    <?php
    $xml = <<<'EOF'
    <?xml version="1.0" encoding="UTF-8" ?>
    <body>
    <keyword>3333</keyword>
    <order>0</order>
    <pagesize>10</pagesize>
    <pagenum>1</pagenum>
    <corporation_id>3398351028</corporation_id>
    </body>
    EOF;
    $PublicAccountServerIP = "218.205.81.33";

    $header[]="Host: $PublicAccountServerIP";
    $header[]="Accept-Encoding: gzip";
    $header[]="Content-Type: text/xml";
    //自定义头部--start
    $header[]="msgname: getpubliclist";
    $header[]="version: 1.0.0";
    $header[]="userid: +8618867101652_3398351028@li726-26";
    $header[]="AuthType:httpdigest";
    //自定义头部--end
    $header[]="Content-Length: ".strlen($xml);

    $url = "http://$PublicAccountServerIP/padata/eclient/msg";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_HEADER, 0);  #必须把应答头开启
    curl_setopt($ch, CURLOPT_HEADER, 1); #头部有result: 000000 字段,表示应答请求信息,参考接口说明
    $ret = curl_exec($ch);
    $headSize = curl_getinfo($ch,CURLINFO_HEADER_SIZE); #获取头部数据大小,此项必须增加进来
    curl_close($ch);

    $strHead = substr($ret,0,$headSize-2); # 多余
    $strBody = substr($ret,$headSize);
    echo $strHead;
    echo " ";
    echo $strBody;
    echo " ";
    echo getHttpField($strHead,'result');

    //获取http请求头部的某个头域的值
    function getHttpField($strHead,$strField){
    if(!$strHead || !$strField){return null;}
    $arr = explode(" ",$strHead);
    foreach($arr AS $v){
    $pos = strpos($v,':');
    if($pos){
    $field = substr($v,0,$pos);
    $value = trim(substr($v,$pos+1));
    if( $field == $strField){
    return $value;
    }
    }
    }
    return null;
    }


    ?>

    重要说明:

  • 相关阅读:
    js反爬:请开启JavaScript并刷新该页
    VIEWSTATE等参数处理
    VM+CentOS+Hadoop+Spark集群搭建
    从入门到自闭之Python入门
    从入门到自闭之Python软件命名规范
    从入门到自闭之Python序列化
    从入门到自闭之Python名称空间
    从入门到自闭之Python函数初识
    从入门到自闭之Python随机模块
    从入门到自闭之Python时间模块
  • 原文地址:https://www.cnblogs.com/voiphudong/p/4168693.html
Copyright © 2011-2022 走看看