php curl实现application-x-www-form-urlencoded提交

php之curl 2020-01-18 阅读 275 评论 0

php使用 curl 实现 application-x-www-form-urlencoded 类型的表单数据,跟 curl使用multipart/form-data上传数据 的实现方式有点像,不同的是数据的传递上,前者可以使用 http_build_query 生成 URL-encode 之后的请求字符串,并将编码后的字符串放在 CURLOPT_POSTFIELDS。

实现代码

function post($url, $data, $headers)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true, // 如果成功只将结果返回,不自动输出任何内容
        CURLOPT_TIMEOUT => 0,   // 设置curl允许执行的最长秒数
        CURLOPT_POST => true,   // 注意 CURLOPT_POST 一定要在 CURLOPT_POSTFIELDS 前面
        CURLOPT_POSTFIELDS => $data // 请求的数据内容
    ));
    // 设置请求头
    if (!empty($headers)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $errno = curl_errno($curl);
    if ($errno) {
        return false;
    }
    curl_close($curl);
    return $response;
}

调用示例

下面是一个发送数组的例子

$arr = [
    "name" => "用户名",
    "password" => "密码",
    "arr[0]" => 0,
    "arr[1]" => 1,
];
$data = http_build_query($arr);
$headers = ["User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"];
echo post("http://localhost/response.php", $data, $headers);

response.php 执行打印 post 值 和 Content-Type

print_r($_REQUEST);
$contentType = $_SERVER["CONTENT_TYPE"];
print_r($contentType);

输出

Array
(
    [name] => 用户名
    [password] => 密码
    [arr] => Array
        (
            [0] => 0
            [1] => 1
        )

)
application/x-www-form-urlencoded

以下是phpstorm断点调试的截图

不用指定 Content-Type,请求头Content-Type 会自动设置成 application/x-www-form-urlencoded。

最后更新 2020-01-18
MIP.watch('startSearch', function (newVal, oldVal) { if(newVal) { var keyword = MIP.getData('keyword'); console.log(keyword); // 替换当前历史记录,新增 MIP.viewer.open('/s/' + keyword, {replace: true}); setTimeout(function () { MIP.setData({startSearch: false}) }, 1000); } }); MIP.watch('goHome', function (newVal, oldVal) { MIP.viewer.open('/', {replace: false}); });