Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cURL to upload a file without @ symbol?

I have a slight problem here, how can I tell cURL specifically to attach a file to a request?

If I am uploading a file with cURL, then the common method is to attach it as part of POST data array with the value having @ in front of it, for example:

CURLOPT_POSTFIELDS=>array('my-file'=>'@my-file.txt')

This would obviously work, but I have two problems with it:

  • What if it is not actually a file I am uploading? What if my POST value actually IS '@my-file.txt' and it attempts to upload the file instead? It creates a loophole I am desperately trying to avoid.
  • How can I upload a file from a URL? Would I have to download it, store it in temporary folder and then attach it with @ from that temporary folder? Why can't I give cURL just contents that I wish to use as file?

cURL CURLOPT_INFILE is not an option, since it won't show up as part of $_FILES array.

It seems like such a loophole in cURL to be dependent on @ symbol in the POST field value. Is there a way around it? Why isn't there a CURLOPT_FILEFIELDS array? Command-line cURL has a separate flag for this (-F), but I don't see it as an option in PHP for some reason.

Any help would be greatly appreciated, thanks!

like image 354
kingmaple Avatar asked Oct 22 '22 13:10

kingmaple


2 Answers

In case anyone is viewing this in 2019 and beyond after finding this result on Google (as I have) the issue has been resolved as per this bug fix.

You can now use CURLFile to send files via PHP CURL requests as below:

$fullpath = '/var/www/html/website/test.png';
$mime = 'image/png';
$publicname = 'testpic';
$cfile = curl_file_create($fullpath,$mime,$publicname);
$fields[$publicname] = curl_file_create($fullpath,$mime,$publicname);

Which would be then used in e.g.

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

Further information can be found here.

like image 109
Max Avatar answered Oct 27 '22 09:10

Max


What I ended up doing is detecting if any of the input data started with an @ symbol and if they did, then submitting them as a GET variable (as part of the submit URL in cURL). It does not help with all cases (such as when a large string is submitted that starts with an @), but cuts out the problems I had with Twitter handles.

like image 27
kingmaple Avatar answered Oct 27 '22 11:10

kingmaple