Before I start asking, I want to mention that I am re-learning PHP after a long break from it. Please be gentle. Also, I know I can use libraries like curl to do some of these things, but I want to understand how PHP itself works.
I'm trying to submit an http GET request to the Microsoft API (Identity Platform). Here is my code:
<?php $data = array ( 'client_id' => '6731de76-14a6-49ae-97bc-6eba6914391e', 'state' => '12345', 'redirect_uri' => urlencode('http://localhost/myapp/permissions') ); $streamOptions = array('http' => array( 'method' => 'GET', 'content' => $data )); $streamContext = stream_context_create($streamOptions); $streamURL = 'https://login.microsoftonline.com/common/adminconsent'; $streamResult = file_get_contents($streamURL, false, $streamContext); echo $streamResult; ?>
When I try to execute the above code, I get: Error snippet
In contrast, using the following code, the http request works fine:
<?php $streamURL = 'https://login.microsoftonline.com/common/adminconsent?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&state=12345&redirect_uri=http://localhost/myapp/permissions'; $streamResult = file_get_contents($streamURL); echo $streamResult; ?>
Can anyone provide insight into why the first example fails and the second example succeeds? My thought is there must be some kind of syntax error. Thanks in advance.
The
content
parameter is used for the request body and applies to POST and PUT requests. But the GET parameters will not appear in the body, but directly in the URL. So your first example just makes a GET request to the base URL, without any parameters at all. Also note that themethod
parameter already defaults to GET, so you can skip the whole stream bit.You can build the URL like this:
Then:
Or just cram it all into one statement:
Or use
$url
to providecurl_init()
or Guzzle or similar.