I spent a little bit of time trying to get my PHP to work with curl uploads. I’ve seen a couple of websites that have varying information, sometimes not really accurate nor helpful on the matter. So I want to present a barebones working example using PHP to demonstrate how to do a file upload with the PHP curl version:
$url = ‘/path/to/your/curl/service’;
$ch = curl_init($url);
$params = array(‘file’ => ‘@/tmp/myfile.jpg’, ‘id’ => 1234);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ret = curl_exec($ch);
Here are the pertinent and points about doing things this way vs a normal post:
- You MUST set the CURLOPT_POST option to true/1 (this will inform curl to do the multipart)
- You must prefix the file you want to upload with the at (@) symbol. This will tell curl where to upload the file from.
- You must leave the POSTFIELDS as key/value pairs. Usually, with regular POST calls, you would have to do something like key1=val1&key2=val2&key3=val3.
You might not necessarily need to set the type. I think that aspect may depend on the receiving service.
Hopefully, this tip will make your life easier when it comes to uploading files.
Leave a Reply
You must be logged in to post a comment.