php - PHP curl提交空有效载荷
问题描述
我正在尝试使用 PHP curl 提交带有一些文件的有效负载。这是我的submit.php
<?php
$url = "http://example.com/receive.php";
$payload = array();
$payload['resource_name'] = 'hello world';
$payload['resource_file'] = curl_file_create("test-pdf.pdf");
$headr = array();
//$headr[] = 'Content-Type: multipart/form-data';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($payload));
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close ($ch);
print_r($response);
echo "\n";
这是我的http://example.com/receive.php
<?php
print_r($_REQUEST);
print_r($_FILES);
当我从命令行运行时php submit.php
,我得到了这个结果:
Array
(
[resource_name] => hello world
[resource_file] => Array
(
[name] => test-pdf.pdf
[mime] =>
[postname] =>
)
)
Array
(
)
为什么我的$_FILES
数组是空的?
如果我启用该multipart/form-data
行,那么两者$_REQUEST
和$_FILES
都是空的。我究竟做错了什么?如何在receive.php 中同时填充$_REQUEST 和$_FILES 数组?
解决方案
删除http_build_query
并解决问题。
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
原因是http_build_query
它将生成 URL 编码的查询字符串x-www-form-urlencoded