Last Updated: February 25, 2016
·
15.4K
· leonardchallis

Use http_build_query() with CURLOPT_POSTFIELDS in PHP

When yuo use an array when you set the cURL option HTTPPOSTFIELDS it will change the request content-type to multi-part form data, which can screw things up. You can use a url encoded string, like:

'something=' . rawurlencode('value') . '&foor=' . rawurlencode('bar')

but instead consider using the PHP built-in function httpbuildquery(). This will take an array (which is cleaner) and build a string similar to the previous example for you, including URL escaping where necessary and using correct & and & correctly.

This will enable you to do something like this:

$field = array('something' => 'value', 'foo' => 'bar');
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields)

This is especially important when using APIs with authentication like OAuth where you need to generate signatures.