php - 在 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"];
}
我正在尝试发送一个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);
该文件作为 $_POST 发送,而不是在 $_FILES 中发送。我发送的内容也作为字符串接收$_POST['Image']
我尝试使用本文中给出的答案here
if (function_exists('curl_file_create')) {
$cFile = curl_file_create($file_name_with_full_path);
} else {
$cFile = '@' . realpath($file_name_with_full_path);
}
在发送之前使用上面的代码片段准备文件。由于我使用的是 PHP 5.5+ 版,因此创建了一个对象。它给出了以下错误
类 CURLFile 的对象无法转换为字符串
当我将所有参数连接到$fields_string
解决方案
使用 cURL 上传文件将像常规 HTTP FILE POST 一样可用,并且应该可以通过 $_FILE 全局变量进行处理,以与使用 PHP 处理常规文件上传相同的常规方式进行处理。
测试.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}";
测试响应.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”相同的路径中,以获得如图所示的输出。
推荐阅读
- python - 拟合 Keras 模型会产生错误“常量折叠失败:无效参数:不支持的类型:21”
- git - 如何在 Android Studio 中的 git commit diff 期间编辑文件?
- c# - 从 Excel 获取数据 - 索引超出范围
- rust - 无法通过 arm-none-eabi-gdb 命令连接到 GDB 服务器
- linux - 如何将递归目录复制到平面目录
- android - FCM 不会立即发送数据消息
- django - 检查用户是否有新的发行说明并通知他
- android - 无法读取未定义的属性“导航”-本机反应
- javascript - 当 div 有活动类时不要执行该函数
- javascript - antd table 在分页点击时向上滚动