首页 > 解决方案 > 在 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

标签: phpcurl

解决方案


使用 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”相同的路径中,以获得如图所示的输出。


推荐阅读