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_POSTis specifically designed for standard POST requests, handling the request body encoding and headers appropriately.CURLOPT_CUSTOMREQUESToverrides the default request method, and when used alongsideCURLOPT_POST, it can disrupt how the server parses your JSON payload, leading to theINVALID_REQUESTerror.
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
- Removed
CURLOPT_CUSTOMREQUEST => 'POST': This eliminates the conflict between request method settings, ensuring the server receives a properly formatted POST request. - Used
json_encodeinstead 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. - Standardized
Content-Typeheader: While many servers accept lowercase, usingContent-Type: application/jsonfollows HTTP standards and avoids potential edge cases. - 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
相关产品推荐
相关产品推荐

