0
votes

I'm trying to send json object to server and to get variable from the header of response. when I tried to do this request using postman, it's work great. but in PHP I get errors.

enter image description here

my php code:

$url = 'https://test.com/login';
$postArray = array('email' => '[email protected]', 'password' => 'test');  

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postArray));
$response = curl_exec ($curl);

$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);

var_dump($header);

but the response of header I get in php:

string(370) "HTTP/1.1 500 Internal Server Error Cache-Control: no-cache, no-store, max-age=0, must-revalidate Content-Type: application/json;charset=UTF-8 Date: Wed, 13 Dec 2017 09:48:26 GMT Expires: 0 Pragma: no-cache Server: nginx/1.10.1 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Content-Length: 320 Connection: keep-alive "

how to fix the code to make it work? thank you very much.

update: I add to code:

curl_setopt($curl, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

and the problem solved. thank you

1
Start in your PHP error log.marekful
@marekful there is no errors in log, because the php work great. the request sent successfully and get the response. but why how to make the request to work like in postman?admin sites
PHP works great when you send from Postman but not when this cURL request is sent. In this latter case it generates a server error which is most likely logged. Please...marekful
@marekful ohh, I get what you mean. but the server who get my request it's not mine, so I can't access to his error logs...admin sites
Then set up a script on your own server that logs request headers and body, and compare what you get for your postman and your curl request. With postman, you are sending the data as “raw”, whereas cURL probably automatically added a Content-Type: application/x-www-form-urlencoded or sth. like that.CBroe

1 Answers

0
votes

As the content is json you need to use multipart/form-data :

curl_setopt($curl, CURLOPT_HTTPHEADER, array("content-type: multipart/form-data;"))