You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中获取外部API发送的CURL POST请求参数?

问题:PHP无法获取CURL POST提交的参数?

外部API向我的PHP脚本发送如下CURL POST请求:

$params=['productId'=>'123abc', 'quantity'=>100];
$defaults = array(
    CURLOPT_URL => 'https://my-url/test.php',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($defaults));
$result = curl_exec($ch);

我尝试用两种方式获取参数:

  1. 直接读取$_POST:
error_log('result $_POST ' . json_encode($_POST));

日志显示为空数组。

  1. 读取php://input:
$post = file_get_contents('php://input');
error_log('result $post ' .json_encode($post));

日志显示为空字符串。

请问该如何解决?


解决方法

原因分析

当CURL的CURLOPT_POSTFIELDS传入数组时,CURL会自动将请求的Content-Type设为*multipart/form-data*。如果PHP环境无法正确解析该格式(如配置限制、框架拦截),就会出现$_POST为空的情况;而php://input本身就无法读取multipart/form-data格式的原始请求体(PHP会自动解析到$_POST/$_FILES,解析失败则全部为空)。

方案一:修改发送方的CURL请求(推荐)

让发送方将参数数组转为URL编码字符串,强制使用*application/x-www-form-urlencoded*格式,这样PHP的$_POST就能正常解析:

$params=['productId'=>'123abc', 'quantity'=>100];
$defaults = array(
    CURLOPT_URL => 'https://my-url/test.php',
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($params), // 用http_build_query转换数组
);
$ch = curl_init();
curl_setopt_array($ch, $defaults);
$result = curl_exec($ch);

修改后,接收方直接用$_POST['productId']和$_POST['quantity']就能拿到参数。

方案二:接收方手动处理(无法修改发送方时)

如果无法调整发送方的请求,可先检查PHP配置:

  • 确保enable_post_data_reading配置为On(默认开启)
  • 确认post_max_size和upload_max_filesize的值足够容纳请求数据(避免因数据过大被丢弃)

若配置正常仍无法解析,可手动解析multipart/form-data请求体,示例代码如下(仅作参考):

$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (strpos($contentType, 'multipart/form-data') !== false) {
    $boundary = substr($contentType, strpos($contentType, 'boundary=') + 9);
    $rawData = file_get_contents('php://input');
    $parts = explode("--$boundary", $rawData);
    $postData = [];
    foreach ($parts as $part) {
        if (trim($part) === '' || strpos($part, '--') !== false) continue;
        // 分离头部和内容
        list($header, $value) = explode("\r\n\r\n", $part, 2);
        $value = trim($value);
        // 提取参数名
        if (preg_match('/name="([^"]+)"/', $header, $matches)) {
            $key = $matches[1];
            $postData[$key] = $value;
        }
    }
    // 现在$postData里就有productId和quantity了
    error_log('result postData ' . json_encode($postData));
}

内容的提问来源于stack exchange,提问作者nick rimmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:41:31