Sergio Suarez Sergio Suarez - 1 year ago 79
PHP Question

how to POST CURL with data and headers in PHP

i would like to make a CURL to get an auth tokken.

The platform dev forum give me that:

curl -X POST \
--header 'Content-Type: application/json; charset=utf-8' \
--header 'Accept: application/json' \
-d '{"email":"MY_EMAIL","password":"MY_PASSWORD"}' \

How do i make that work in PHP?

Answer Source

You can do it like below:-

$data_string = '{"email":"MY_EMAIL","password":"MY_PASSWORD"}';                                                                                   

$ch = curl_init('');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json; charset=utf-8',
    'Accept: application/json'

$result = curl_exec($ch);
if (curl_errno($ch)) {
   echo 'Error:' . curl_error($ch);
curl_close ($ch);

I run it and found below response (because i don't have mail-id and password):-

But the pleasant part is code executed successfully and when you will provide right credentials then it will give you correct output.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download