简体   繁体   中英

Posting parameters and array in header in CURL using PHP

i am facing an issue i just need to send an array in header and some parameters in body but when i add

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Token:'.$token));

this line sends token but parameters array get empty but when i just remove the line, parameters successfully send but token is missing

here is the code have look:

      $data = array(

        'name' => $_POST['name'],
        'city' => $_POST['city'],
        'mobileNo' => $_POST['mobileNo'],
      );

      $params = http_build_query($data);
      $curl = curl_init('URL');
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_POST, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
      curl_setopt($curl, CURLOPT_HTTPHEADER, 
      array('Token:'.$token));
      $result = curl_exec($curl);

It is because you overwrite headers and because of that missing content type header. You must add that header to your headers array:

curl_setopt($curl, CURLOPT_HTTPHEADER,array(
'Token: '.$token,
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($params)
));

edit: I've updated post to the working solution

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