Andurit
Andurit

Reputation: 5762

HTTP POST Request on REST API with specific header [PHP]

I need to send give some data to rest webservice. I already try to simulate that backend API works correctly but I just don't know how to authorize to that API via HEADER.

In header there should be an: Authorization set on Bearer token

This is what i did try but without any success.

$host = "www.example.com";
$path = "/path/to/backend";
$arr = array('caseNumber' => '456456787');
$data = json_encode($arr);
$token = "ThisIsSomeLongToken";

header("POST ".$path." HTTP/1.1\r\n");
header("Host: ".$host."\r\n");
header("Content-type: application/json\r\n");
header("Authorization: Bearer ".$token." \r\n");
header("Content-length: " . strlen($data) . "\r\n");
header("Connection: close\r\n\r\n");
header($data);

I'm new in webservices in PHP so I don't even know if this is correct but it doesn't throw any error and also doesn't do anything with webservice.

May I hope for some lead in PHP REST API with headers? Thanks

Upvotes: 3

Views: 12875

Answers (1)

Jan.J
Jan.J

Reputation: 3080

You cannot send post request by using header() function. You should use cURL for that. Check documentation here.
This will probably do what you want:

$host = "www.example.com";
$path = "/path/to/backend";
$arr = array('caseNumber' => '456456787');
$token = "ThisIsSomeLongToken";

$ch = curl_init();

// endpoint url
curl_setopt($ch, CURLOPT_URL, $host . $path);

// set request as regular post
curl_setopt($ch, CURLOPT_POST, true);

// set data to be send
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr));

// set header
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Bearer: ' . $token));

// return transfer as string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

Upvotes: 6

Related Questions