在PHP中使用CURL发送文件和参数
我正在编写一个PHP脚本,它将一个文件和一组参数传递到在PHP中使用CURL发送文件和参数,php,curl,Php,Curl,我正在编写一个PHP脚本,它将一个文件和一组参数传递到upload.PHP 下面是upload.php if (!empty($_FILES["Image"])) { $user_id = $_POST["user_id"]; $user_name = $_POST["user_name"]; $file_name = $_FILES["Image"]["name"]; }
upload.PHP
下面是upload.php
if (!empty($_FILES["Image"])) {
$user_id = $_POST["user_id"];
$user_name = $_POST["user_name"];
$file_name = $_FILES["Image"]["name"];
}
我正在尝试发送一个curl
请求,该请求传递这些参数
function post($file) {
$url = 'http://localhost/mc/upload.php';
$fields = array(
'user_id' => "test_id",
'user_name' => "test_user",
'Image' => '@' . $file
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
文件以$\u POST的形式发送,而不是以$\u文件的形式发送。我发送的内容在$\u POST['Image']
我试着用这篇文章给出的答案
在发送文件之前,请使用上述代码段准备文件。因为我使用的是PHP5.5+版本,所以创建了一个对象。它给出了以下错误
类CURLFile的对象无法转换为字符串
当我将所有参数连接到
$fields\u string
时,会发生此错误。使用cURL上传文件将变得像普通的HTTP文件帖子一样可用,并且应该可以通过$\u FILE全局变量使用与使用PHP处理常规文件上传相同的常规方式来处理
test.php
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, "http://localhost/Projects/Test/test-response.php");
curl_setopt($cURL, CURLOPT_POST, true);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_POSTFIELDS, [
"ID" => "007",
"Name" => "James Bond",
"Picture" => curl_file_create(__DIR__ . "/test.png"),
"Thumbnail" => curl_file_create(__DIR__ . "/thumbnail.png"),
]);
$Response = curl_exec($cURL);
$HTTPStatus = curl_getinfo($cURL, CURLINFO_HTTP_CODE);
curl_close ($cURL);
print "HTTP status: {$HTTPStatus}\n\n{$Response}";
test-response.php
print "\n\nPOST";
foreach($_POST as $Key => $Value)print "\n\t{$Key} = '{$Value}';";
print "\n\nFILES";
foreach($_FILES as $Key => $Value)print "\n\t{$Key} = '{$Value["name"]}'; Type = '{$Value["type"]}'; Temporary name = '{$Value["tmp_name"]}'";
输出
HTTP status: 200
POST
ID = '007';
Name = 'James Bond';
FILES
Picture = 'test.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76B5.tmp'
Thumbnail = 'thumbnail.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76C6.tmp'
我假设您将相关的2个图像保存在与“test.php”相同的路径中,以获得如图所示的输出。这是否回答了您的问题?我不明白你为什么需要“curl_setopt($ch,CURLOPT_HTTPHEADER,array($Content Type:image/jpeg”);”?@brokerswear当我尝试你分享的答案时,它给了我以下错误:
类CURLFile的对象无法转换为字符串(
curl_setopt($ch,CURLOPT_HTTPHEADER,array($Content Type:image/jpeg))
通过删除这一行,我能够传递$\u POST
参数。但在访问$\u文件['Image']
HTTP status: 200
POST
ID = '007';
Name = 'James Bond';
FILES
Picture = 'test.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76B5.tmp'
Thumbnail = 'thumbnail.png'; Type = 'application/octet-stream'; Temporary name = 'C:\Windows\Temp\php76C6.tmp'