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

PHP中Curl请求无法返回预期响应问题求助(Postman/Reqbin可正常运行)

Fixing PHP cURL POST Request Returning INVALID_REQUEST Error

I see the issue with your PHP cURL implementation — the problem comes from conflicting request method settings that are causing the server to misinterpret your request body. Let's break this down and fix it.

The Root Cause

Your code sets both CURLOPT_POST => true and CURLOPT_CUSTOMREQUEST => 'POST'. While both seem related to POST requests, they don't play well together:

  • CURLOPT_POST is specifically designed for standard POST requests, handling the request body encoding and headers appropriately.
  • CURLOPT_CUSTOMREQUEST overrides the default request method, and when used alongside CURLOPT_POST, it can disrupt how the server parses your JSON payload, leading to the INVALID_REQUEST error.

Fixed PHP Code

Here's the corrected version of your code, with key improvements:

$curl = curl_init();

// Use standard capitalization for Content-Type header (more compliant)
$headers = array(
    "Content-Type: application/json"
);

// Use an array + json_encode for safer, more maintainable JSON payload
$postDataArray = [
    "Header" => ["Token" => "xyz"],
    "Body" => [
        "Email" => "abc@gmail.com",
        "FirstName" => "test",
        "Surname" => "test"
    ]
];
$postData = json_encode($postDataArray);

$opt_arr = array(
    CURLOPT_URL => 'http://example.com',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_POST => true, // Keep this for standard POST handling
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => $postData
);

curl_setopt_array($curl, $opt_arr);

$resp = curl_exec($curl);

// Add error checking to debug future issues
if(curl_errno($curl)){
    echo 'Curl Error: ' . curl_error($curl);
}

curl_close($curl);

echo $resp;

Key Changes Explained

  1. Removed CURLOPT_CUSTOMREQUEST => 'POST': This eliminates the conflict between request method settings, ensuring the server receives a properly formatted POST request.
  2. Used json_encode instead of manual JSON: Manually writing JSON strings is prone to typos (like missing commas or quotes). Using an array and encoding it guarantees valid JSON.
  3. Standardized Content-Type header: While many servers accept lowercase, using Content-Type: application/json follows HTTP standards and avoids potential edge cases.
  4. Added cURL error checking: This helps you quickly diagnose issues if the request fails again (e.g., network errors, invalid URLs).

This should match the behavior of your working native curl command and return the expected success response.

内容的提问来源于stack exchange,提问作者Ahmed Syed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 17:13:13