首页 > 解决方案 > 使用 Curl 和 PHP 将文件发送到 Anonfile

问题描述

我正在尝试在anonfile上使用 curl 和 PHP 发送文件,但我得到了这个 json:

{"status":false,"error":{"message":"没有选择文件。","type":"ERROR_FILE_NOT_PROVIDED","code":10}}

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://anonfile.com/api/upload");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'test.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);
print_r($server_output);
curl_close ($ch);

换句话说,如何将这个命令翻译成 PHP?

curl -F "file=@test.txt" https://anonfile.com/api/upload

我尝试了几个例子,但仍然没有线索

$target_url = 'https://anonfile.com/api/upload';
$args['file'] = '@/test.txt';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;

标签: phpcurl

解决方案


curl_setopt($ch, CURLOPT_POSTFIELDS,'test.txt');

不起作用,因为它实际上只是发送文字字符串test.txt

$args['file'] = '@/test.txt';

因为@上传文件的前缀在 PHP 5.5 中已被弃用,在 PHP 5.6 中默认禁用,在 PHP 7.0 中被完全删除,所以无法正常工作。在 PHP 5.5 及更高版本中,使用CURLFilemultipart/form-data格式上传文件。

从 PHP 5.5+ 开始(在这一点上很古老),

curl -F "file=@test.txt" https://anonfile.com/api/upload

翻译成

$ch=curl_init();
curl_setopt_array($ch,array(
    CURLOPT_URL=>'https://anonfile.com/api/upload',
    CURLOPT_POST=>1,
    CURLOPT_POSTFIELDS=>array(
        'file'=>new CURLFile("test.txt")
    )
));
curl_exec($ch);
curl_close($ch);

推荐阅读