简体   繁体   中英

cURL Post Data Not Sending

I am trying to send POST data via cURL however it is not sending the data, however when I send them as GET variables it is sending, does anyone know what the problem could be?

curl_setopt_array($ch, array( 
    CURLOPT_URL => "local.new.api.test.com/authenticate/"
)); 

$data = array(
    'username'  =>  'test',
    'password'          =>  'test'
);  

$data_string = json_encode($data);  

curl_setopt($ch, CURLOPT_POST, TRUE);                                                                   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);   
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);    

CURLOPT_POSTFIELDS is not a json encoded string. It requires a query string (similar to the query string in the URL-s after the question mark).

This should work:

$data_string = http_build_query($data, '', '&');

Or you can let the cURL extension to do the dirty work and pass an array with key-value pairs as the value:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

From PHP.net

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. If value is an array, the Content-Type header will be set to multipart/form-data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM