【问题标题】:cURL not working with POST datacURL 不适用于 POST 数据
【发布时间】:2023-03-27 11:24:01
【问题描述】:

我正在尝试调试它,但我没有运气。我是否正确发送 POST 数据?

if (isset($_POST['chrisBox'])) {

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.associates.com/send-email-orders.php");
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_POST['chrisBox']);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$ex = curl_exec($curl);
echo 'email';
$email = true;

}

【问题讨论】:

    标签: php debugging curl


    【解决方案1】:

    $_POST请求中发送的参数需要采用-的形式

    key=value&foo=bar
    

    您可以为此使用 PHP 的 http-build-query 函数。它会从一个数组中创建一个查询字符串。

    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($_POST));
    

    如果你只想传递一个参数,你仍然需要将它包装在一个数组或对象中。

    $params = array(
      'stack'=>'overflow'
    );
    
    http_build_query($params);     // stack=overflow
    

    【讨论】:

    • 我在想,因为它是表单的一部分,它已经被编码了。上面的这个函数对 key->value 关系进行了编码。对吗?
    • @wow - 是的。它创建一个 URL 编码 查询字符串。任何非法的 URL 字符都会被转义。
    【解决方案2】:

    CURLOPT_POSTFILEDS 需要一个 urlencoded 字符串或数组作为参数。阅读PHP Manual curl_setopt。更改了您的示例,现在它使用了 urlencoded 字符串。

    if (isset($_POST['chrisBox'])) {
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://www.associates.com/send-email-orders.php");
        curl_setopt($curl, CURLOPT_POST, TRUE);
        curl_setopt($curl, CURLOPT_POSTFIELDS, 'chrisBox=' . urlencode($_POST['chrisBox']));
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, FALSE);
        curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
        $ex = curl_exec($curl);
        echo 'email';
        $email = true;
    }
    

    【讨论】:

      【解决方案3】:
      $ex = curl_exec($process);
      if ($ex === false)
      {
          // throw new Exception('Curl error: ' . @curl_error($process));
          // this will give you more info
          var_dump(curl_error($process));
      }
      

      【讨论】:

        猜你喜欢
        • 2015-09-19
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多