How to pass custom header to RESTful call?
10,755
Solution 1
You could use stream_context_create like this:
<?php
$options = array(
'http'=>array(
'method'=>"GET",
'header'=>"CustomHeader: yay\r\n" .
"AnotherHeader: test\r\n"
)
);
$context=stream_context_create($options);
$data=file_get_contents('http://www.someservice.com/api/fetch?key=1234567890',false,$context);
?>
Solution 2
You could use curl. For example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.someservice.com/api/fetch?key=1234567890');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Header: value'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Author by
Jake Wilson
Experienced in developing tools for 3D animation, motion capture, video game and movie production, web development, Android development, responsive design, etc...
Updated on June 14, 2022Comments
-
Jake Wilson almost 2 years
There are some web service APIs that I need to connect to for my website. Most of the APIs involve something like this:
$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890
But one web service requires the API key to be set in a custom HTTP header. How do I make the request to this API url and pass the custom header at the same time?
-
cmbuckley almost 12 years+1 for the best solution to the question; however it's probably worth mentioning curl as a fully-fledged alternative.
-
Rob almost 12 yearsI was typing up the same answer til you posted yours so I provided a curl example instead.
-
Jake Wilson almost 12 yearsI agree curl is a good alternative (and more useful in many cases) but I need to use
file_get_contents
in this situation. Good answer! Thanks! -
Tanmoy Bhattacharjee over 8 yearsIs it possible to redirect using this method? I am able to implement it but not able to redirect to "someservice.com/api/fetch?key=1234567890"