php中模拟post,get请求和接受请求详细讲解

在php中我们经常用到curl拓展来进行模拟post、get请求,下面就来具体说说怎么模拟:

一、首先模拟post请求:

function http_post_data($url, $query_data,$timeout=30) {
if(is_array($query_data)){
$post_str = http_build_query($query_data); //变成 a=1&b=2形式 会进行urlencode()转换
} $curl = curl_init(); // 初始化curl curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果 curl_setopt($curl, CURLOPT_POST, true); // post方式 curl_setopt($curl, CURLOPT_POSTFIELDS, $post_str); // post传输数据 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); // 设置等待时间 curl_setopt($curl,CURLOPT_TIMEOUT,$timeout); // 设置超时 if(strtolower(substr($url,0,5))=='https'){ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } //curl_setopt($curl,CURLOPT_CAINFO,dirname(__FILE__).'/cacert.pem') //如果地址是https协议,且CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST打开了,则需要加载证书
//根据http://curl.haxx.se/ca/cacert.pem 下载的证书,添加上面注册的这个选项就可以运行正常了 $header = array( "Content-Type: application/x-www-form-urlencoded; charset=UTF-8" ); curl_setopt($curl, CURLOPT_HTTPHEADER, $header); $content = curl_exec($curl);//返回内容 $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);//返回状态码 curl_close($curl); if($status=='200') return $content; else return false; }

模拟get请求就很简单了,直接将post方式改为false,将post传输数据项注释;然后将请求的参数拼接到路径后面就可以了。

上面这种方式如果我们传送数组 或者 a=1&b=2 这样格式的字符串,接受这样的传送,直接用$_POST 或者$_REQUEST就可以获取对应参数的值,至于其他的怎么下面再说。

二、不同的请求头

但有时候我们想要传送json和文件时上面这种方式可能就有点行不通,需要像下面一样该改变请求头

请求json数据:

$header[] = "Content-Type: application/json; charset=utf-8";//声明请求的内容为json
$header[] = "Content-Length:".strlen(json_encode($data));//请求内容的长度

上传文件:

$header[] = "Content-Type:multipart/form-data";//用$_FILES接受传送的文件

请求html数据:

$header[] = "Content-Type:text/html;charset=utf-8";

请求xml数据:

$header[] = "Content-Type:text/xml;charset=utf-8";

还有一种:这种方式,如果浏览器接受到内容,会直接当做纯文本,不会进行html或者xml解析。

$header[] = "Content-Type:text/plain;charset=utf-8";

三、接受请求的几种方式

  1、数组或者a=1&b=2类的字符串

    这个不用多说直接用我们常用的$_GET、$_POST、$_REQUEST就可以接受

  2、json、xml、html或者其他字符串

    PHP默认只识别application/x-www.form-urlencoded标准的数据类型,对xml内容、json内容、html内容的内容无法解析为$_POST数组,因此会保留原型,可以交给file_get_contents(‘php://input’)接收,也可以用$GLOBALS['HTTP_RAW_POST_DATA']。

$xml = file_get_contents("php://input");
//或者
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];

    php://input 允许读取 POST 的原始数据。和$GLOBALS['HTTP_RAW_POST_DATA'] 比起来,它给内存带来的压力较小,并且不需要任何特殊的 php.ini 设置。同时两者皆不能用于接收enctype="multipart/form-data"形式的数据。

四、file_get_contents()模拟请求

function post($url, $content){
        $ctx = array(
            'http' => array(
                'method' => 'POST',//或者GET
                'header' => "Content-Type: application/x-www-form-urlencoded",
                'content' => $content
            )
        );
        return file_get_contents($url, false, stream_context_create($ctx));
}

这种方式也可以快速模拟post、get请求,不过这种方式在访问量不大的情况下还没什么问题,如果访问量大可能就会出问题;所以一般在项目中不太推荐这种请求方式。