如何在PHP中使用curl -T / - upload-file和POST?

如何在PHP中使用curl -T /  -  upload-file和POST?

问题描述:

I'm implementing an integration to an API and according to example in the documentation I need to post a file using -T/--upload-file.

curl -u "username:password" -0 –X POST -T filename.txt -H "Content-Type: text/plain" "http://url"

My solution:

$fp = fopen('/home/myFile.txt', 'rb');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize('/home/myFile.txt'));

The problem however is that CURLOPT_INLINE only works when using PUT, whereas the example is using POST.

I've seen the following solution but I don't think that's what I'm supposed to use since it doesn't seem to be the same thing as -T. I don't see any mention of key name in the documentation either.

curl_setopt($c, CURLOPT_POST, true);
curl_setopt($c, CURLOPT_POSTFIELDS, array('file'=>'@/home/myFile.pdf'));

Is there a way to do this properly?

If you add --libcurl code.c to your curl command line you'll see exactly which libcurl options it used, and then you'll see that CURLOPT_CUSTOMREQUEST is what you miss in your solution to emulate that command line. Ie the CURLOPT_INFILE approach will assume and default to PUT, but you can override that.