Teiv
Teiv

Reputation: 2635

Change name of upload file in cURL?

I want to upload a file using cURL. Since cURL requires full path to the file so 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 this full path of the file in the request header:

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

But I want it to be just

Content-Disposition: form-data; name="file"; filename="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 simply throws an error message

couldn't open file "file.ext"

Can anybody tell me how to do it please?

Upvotes: 16

Views: 24850

Answers (3)

Rudie
Rudie

Reputation: 53881

New method (since 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 of

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

you can tell cURL to use another filename:

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

That way it will use path/to/file.ext as file source, but file.ext as filename.

You'll need a very absolute path though, so you're probably missing a leading /: /path/to/file.ext. Since you're using PHP, always do a realpath():

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

Or something like that.

Upvotes: 25

Teiv
Teiv

Reputation: 2635

Please correct me if I'm wrong but cURL upload won't work with relative path. It always need an absolute path, likes

$realpath = realpath($uploadfile);

So if someone wants to hide the location to his file on his webserver when uploading, either move it to a temporary folder or use fsockopen() (see this example in PHP Manual's User Contributed Notes)

Upvotes: 13

davidethell
davidethell

Reputation: 12028

Your going to need to put the file in a temporary area and then reference the file from there if you want to hide the true file location. Unfortunately cURL doesn't support sending just binary data or else you could just send the base64 or binary data string instead of a filename reference.

Upvotes: 0

Related Questions