phparrayscurllibcurlnotice

Array 2 string conversion while using CURLOPT_POSTFIELDS


I have following code:

// $postfields = array();
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

My $postfields variable is an array of parameters. And i have a notice there is array to string conversion. It works tho.

I could use http_build_query() function to nullify notice, however i use @path_to_file to include post files. and http_build_query() breaks file includes.

I'm wondering if there is more "proper" way to do this. Without generating a notice.


Solution

  • Are some values of $postfields arrays themselves? This is most likely what's causing the notice. curl_setops expects its third parameter to be an array whose keys and values are strings, as is stated in PHP's manual page for the function, though it might not be very clear:

    This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

    In this quote, the key point is that para1/2 and val1/2 are strings, and if you want, you can provide them as an array where keys are para1 and para2, and values are val1 and val2.

    There are two ways to eliminate the notices.

    The first is to use http_build_query() and replace your uses of @filepath by CURLFile objects. This is only possible if you're using PHP 5.5 or above, unfortunately. The manual's page has a pretty clear and simple example of use.

    If using CURLFiles is not an option for you, then the second way is to json_encode() the values of your $postfields array which are arrays themselves. This isn't elegant, and it requires you to decode the JSON on the other side.