【问题标题】:PHP cURL sending empty parametersPHP cURL 发送空参数
【发布时间】:2018-02-28 07:03:52
【问题描述】:

cURL 对我来说是新的。我正在尝试通过 PHP cURL 集成一个 api。我尝试访问的 api 要求将参数作为键值对发送,而不是 json。他们在文档中的示例 cURL 请求是:

curl -i -X POST -d  'api_key=my_api_key' -d 
'email=john@doe.com' -d "first_name=Joe" -d "last_name=Doe" -d 
"cust_id=cus_401" 
https://serviceurl.com/api/create

我的代码显然正在向他们的 api 发送空参数。

    $service_url = 'https://serviceurl.com/api/create';

    $curl = curl_init($service_url);

    $email = $this->session->userdata('email');

    $postArray = array(
        'api_key' => 'my_api_key',
        'email' => $email,
    );

    $curl_post_data = $postArray;
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);


    $curl_response = curl_exec($curl);
    if ($curl_response === false) {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additioanl info: ' . var_export($info));
    }
    curl_close($curl);
    echo $curl_response;
    echo $info;

任何建议将不胜感激。

【问题讨论】:

  • 他们的例子比你的代码有更多的字段——你只使用了两个——这可能是原因吗?此外 - POST 方法存在细微差别 - application/x-www-form-urlencodedmultipart/form-data 取决于您是使用简单数组作为 POST 数据还是使用 http_build_query 创建数据字符串
  • 其他字段不是必需的。只是 api 密钥和电子邮件参数。您能否进一步说明 POST 方法的区别。我不太明白。谢谢
  • php.net/manual/en/function.curl-setopt.php ~ 寻找CURLOPT_POSTFIELDS 阅读描述。基本上 - If value is an array, the Content-Type header will be set to multipart/form-data 所以这取决于 api 是期待 urlencoded 还是 multipart 数据

标签: php curl


【解决方案1】:

您的 curl php 代码正在发送 multipart/form-data 格式的数据,但从他们的 cli 调用示例可以看出,他们的 api 需要 application/x-www-form-urlencoded 格式的数据。

as explained by the curl_setopt docs,当你给 CURLOPT_POSTFIELDS 一个数组时,它会自动被编码为multipart/form-data,如果你给它一个字符串,application/x-www-form-urlencoded 将自动被假定,这就是他们的 curl cli 调用使用的。

幸运的是,PHP 有一个将数组编码为application/x-www-form-urlencoded 格式的专用函数,称为http_build_query,因此 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($curl_post_data)); 将解决您的apparently sending empty parameters 问题。

另外,如果设置任何选项时出现问题,curl_setopt 将返回 bool(false),您的代码会完全忽略它,并且不会被注意到,您应该解决这个问题,考虑使用捕获错误的 setopt 包装器,喜欢

function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
    $ret=curl_setopt($ch,$option,$value);
    if($ret!==true){
        //option should be obvious by stack trace
        throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . $ch .'. curl_error: '.curl_error($ch) );
    }
    return true;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-03
    • 2017-07-17
    • 2011-03-26
    相关资源
    最近更新 更多