使用PHP file_get_contents发送POST参数未被接收问题求助
问题排查与解决方案
你的代码存在三个核心问题,导致接收端无法获取POST参数:
1. HTTP请求配置错误
- stream_context的http选项中,请求方法的参数名是
method而非type,你写的type => "POST"不会生效,实际可能默认走GET请求(这也是$_POST为空的直接原因)。 - 请求头里混入了jQuery AJAX的专属配置参数(
xhrFields、cache、crossDomain等),这些是前端JS层面的设置,不属于HTTP请求头范畴,会干扰服务器对请求的解析。
2. Content-Type与请求体格式不匹配
你设置了Content-type: multipart/form-data,但用http_build_query生成的是application/x-www-form-urlencoded格式的请求体,两种格式完全不兼容,服务器无法解析出$_POST参数。
3. 文件上传方式错误
直接传递$_FILES['file']['tmp_name']只是本地服务器的临时文件路径,接收端服务器无法访问这个路径,必须读取文件内容并以multipart/form-data格式封装上传。
修正后的发送端代码
// 读取本地临时文件内容 $fileContent = file_get_contents($_FILES['file']['tmp_name']); $fileName = $_FILES['file']['name']; // 生成multipart分隔符 $boundary = '----WebKitFormBoundary' . uniqid(); // 构造符合multipart/form-data规范的请求体 $postdata = "--$boundary\r\n"; // 封装文件字段 $postdata .= "Content-Disposition: form-data; name=\"file\"; filename=\"$fileName\"\r\n"; $postdata .= "Content-Type: application/octet-stream\r\n\r\n"; $postdata .= $fileContent . "\r\n"; // 封装普通参数 $postdata .= "--$boundary\r\n"; $postdata .= "Content-Disposition: form-data; name=\"quality\"\r\n\r\n"; $postdata .= "75\r\n"; $postdata .= "--$boundary\r\n"; $postdata .= "Content-Disposition: form-data; name=\"path\"\r\n\r\n"; $postdata .= "myfile.jpg\r\n"; $postdata .= "--$boundary\r\n"; $postdata .= "Content-Disposition: form-data; name=\"dpi\"\r\n\r\n"; $postdata .= "300\r\n"; // 结束分隔符 $postdata .= "--$boundary--\r\n"; $opts = array('http' => array( 'method' => "POST", 'header' => "Content-Type: multipart/form-data; boundary=$boundary\r\n", 'content' => $postdata, 'timeout' => 30 // 可选,设置请求超时时间 )); $context = stream_context_create($opts); $result = file_get_contents('https://example.com/myphpfile.php', false, $context); echo $result;
修正后的接收端代码
// 文件从$_FILES数组获取,普通参数从$_POST获取 if(isset($_FILES['file'])){ $fileTmpPath = $_FILES['file']['tmp_name']; $fileName = $_FILES['file']['name']; // 可在此处添加文件保存逻辑,比如: // move_uploaded_file($fileTmpPath, '/your/save/path/' . $fileName); } // 使用??运算符避免未定义索引报错 $dpi = $_POST["dpi"] ?? ''; $quality = $_POST["quality"] ?? ''; $path = $_POST["path"] ?? ''; print_r($_POST); print_r($_FILES);
更简洁的替代方案:使用cURL
如果服务器允许使用cURL,推荐用它处理文件上传,代码更简洁且不易出错:
$ch = curl_init('https://example.com/myphpfile.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'file' => new CURLFile($_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['name']), 'quality' => '75', 'path' => 'myfile.jpg', 'dpi' => '300' )); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); curl_close($ch); echo $result;
内容的提问来源于stack exchange,提问作者kiks73
相关产品推荐
相关产品推荐

