3

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

1 Answer 1

6

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); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.