Change file name in cURL?

I want to upload a file using cURL. Since cURL requires a full file path, here is my code:

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

However, cURL will also post the full file path in the request header:

Content-Disposition: form-data; name = "file"; file name = "/path/to/file.ext"

But I want it to be simple

Content-Disposition: form-data; name = "file"; file name = "file.ext"

So, I change the code to

 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 

And then cURL just gives an error message

could not open file "file.ext"

Can anyone tell me how to do this?

+8
post php curl
source share
3 answers

New method (starting with PHP 5.5) using CURLFile :

 $file = new CURLFile('path/to/file.ext'); $file->setPostFilename('file.ext'); 

use it almost the same:

 "file" => $file 

Old method :

Instead

 "file" => "@path/to/file.ext" 

you can tell cURL to use a different file name:

 "file" => "@path/to/file.ext; filename=file.ext" 

Thus, it will use path/to/file.ext as the source of the file, but file.ext as the file name.

You will need a very absolute path, so you probably miss the leading / : /path/to/file.ext . Since you are using PHP, always do realpath() :

 "file" => '@' . realpath($pathToFile) . '; filename=' . basename($pathToFile); 

Or something like that.

+16
source share

Please correct me if I am wrong, but loading cURL will not work with the relative path. He always needs an absolute path, like

 $realpath = realpath($uploadfile); 

So, if someone wants to hide the location of his file on his web server when downloading, either move it to a temporary folder, or use fsockopen () (see this example ) in the User Guide written in PHP)

+8
source share

You will need to place the file in a temporary area and then refer to the file if you want to hide the true location of the file. Unfortunately, cURL does not support sending only binary data, otherwise you can just send base64 or a binary data string instead of a link to the file name.

0
source share

All Articles