zoukankan      html  css  js  c++  java
  • PHP 中的CURL 模拟表单的post提交

    <?php
    $data = ['username'=>'乔峰','skill'=>'擒龙手'];
    $headers = array('Content-Type: application/x-www-form-urlencoded');
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
    curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
    curl_close($curl); // 关闭CURL会话
    echo($result);
    ?>

    这里需要注意的是:

    要想以 x-www-form-urlencoded 方式发送,最关键是发送的数据格式。

    方式from-data试发送的数据用的是array格式,而方式为 x-www-form-urlencoded 时需要用key=value&key2=value2的格式发送,发送的是string型的数据。

    比如我上面from-data数据的为:
    ​​​​​​$data = [
        'username' => '乔峰',
        'skill' => '擒龙手'
    ];
    x-www-form-urlencoded时的数据则要变为
    http_build_query($data);

  • 相关阅读:
    [转]Apache Doris资料汇总
    [算法]最小差值
    如何在Mac上配置iTerm2以及给ITerm2配置lrzsz
    [算法]关于位运算
    [算法]LeetCode 152:乘积最大子序列
    [算法]LeetCode 120:三角形最小路径和
    奇淫巧技之程序启动后在进程列表中隐藏密码等关键信息
    真机调试时遇到“Could not launch *** process launch failed: Security”的解决办法
    Objective-C的 KVC和KVO
    开始python学习了
  • 原文地址:https://www.cnblogs.com/rxbook/p/11776013.html
Copyright © 2011-2022 走看看