在cURL中更改上传文件的名称?

Tei*_*eiv 13 php post curl

我想使用cURL上传文件.由于cURL需要文件的完整路径,所以这是我的代码:

curl_setopt($ch, CURLOPT_POSTFIELDS, array("submit" => "submit", "file" => "@path/to/file.ext"));
curl_exec($ch);
Run Code Online (Sandbox Code Playgroud)

但是,cURL还会在请求标头中发布该文件的完整路径:

内容处理:表格数据; NAME = "文件"; 文件名= "/路径/到/ file.ext"

但我希望它只是

内容处理:表格数据; NAME = "文件"; 文件名= "file.ext"

所以我将代码更改为

curl_setopt($ch, CURLOPT_POSTFIELDS, array("submit" => "submit", "file" => "@file.ext"));
chdir("path/to"); # change current working directory to where the file is placed
curl_exec($ch);
chdir("path"); # change current working directory back
Run Code Online (Sandbox Code Playgroud)

然后cURL只会抛出一条错误消息

无法打开文件"file.ext"

有人能告诉我怎么做吗?

Rud*_*die 20

使用CURLFile的新方法(自PHP 5.5开始):

$file = new CURLFile('path/to/file.ext');
$file->setPostFilename('file.ext');
Run Code Online (Sandbox Code Playgroud)

使用它几乎相同:

"file" => $file
Run Code Online (Sandbox Code Playgroud)

老方法:

代替

"file" => "@path/to/file.ext"
Run Code Online (Sandbox Code Playgroud)

你可以告诉cURL使用另一个文件名:

"file" => "@path/to/file.ext; filename=file.ext"
Run Code Online (Sandbox Code Playgroud)

这样它将path/to/file.ext用作文件源,但file.ext作为文件名.

你需要一个非常绝对的路径,所以你可能错过了一个领先的/:/path/to/file.ext.由于您使用的是PHP,因此请始终执行以下操作realpath():

"file" => '@' . realpath($pathToFile) . '; filename=' . basename($pathToFile);
Run Code Online (Sandbox Code Playgroud)

或类似的东西.


Tei*_*eiv 12

如果我错了请纠正我,但cURL上传不适用于相对路径.它总是需要一条绝对的道路,喜欢

$realpath = realpath($uploadfile);
Run Code Online (Sandbox Code Playgroud)

因此,如果有人想在上传时将位置隐藏在他的网络服务器上的文件中,请将其移动到临时文件夹或使用fsockopen()(请参阅PHP手册的用户贡献说明中的此示例)