PHP中如何获取Curl发送的数据?发送端正常但接收端无输出
问题解决:CURL POST请求后接收端无法获取数据
问题根源在于手动设置了Content-Type: multipart/form-data但未提供正确的boundary分隔符。当你向CURLOPT_POSTFIELDS传入数组时,CURL会自动生成符合规范的multipart/form-data请求(包含自动生成的boundary),但手动添加该Header后,CURL不会自动补充boundary,导致接收端无法解析请求体,最终$_POST为空。
解决方案1:移除手动设置的Content-Type头(推荐)
让CURL自动处理请求头,它会根据CURLOPT_POSTFIELDS的类型生成正确的Content-Type及boundary:
// Prepare subscriber data $data = array( 'name' => "John" ); // Set cURL options $url = "https://www.example.com/end-point.php"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Execute cURL request $response = curl_exec($ch); $curl_error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check if the request was successful if ($http_code >= 200 && $http_code < 300) { echo $response; } else { // Output error message echo "Error"; }
解决方案2:改用application/x-www-form-urlencoded格式
如果希望使用默认的POST表单格式,可将数组转为URL编码字符串,并设置对应Content-Type:
// Prepare subscriber data $data = array( 'name' => "John" ); $post_data = http_build_query($data); // Set cURL options $url = "https://www.example.com/end-point.php"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/x-www-form-urlencoded' )); // Execute cURL request $response = curl_exec($ch); $curl_error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check if the request was successful if ($http_code >= 200 && $http_code < 300) { echo $response; } else { // Output error message echo "Error"; }
接收端代码无需修改,保持echo $_POST['name'];即可正常获取数据。
内容的提问来源于stack exchange,提问作者JojoLapin45
相关产品推荐
相关产品推荐

