phpgetmicrosoft-identity-web

PHP HTTP Request Ignoring Parameter


Before I begin with my question, I will mention that I am re-learning PHP after a long time away from the language. Please be gentle. Also, I know that I could use a library like curl to do some of these things, but I would like to understand how PHP works natively.

I am trying to submit an http GET request to a Microsoft API (Identity Platform). The following 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 and execute the above code, I get this: Error snip

Conversely, with 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 as to why the first example fails while the second succeeds? My thought is that there must be some kind of syntactical error. Thanks in advance.


Solution

  • The content parameter is for the request body, for POST and PUT requests. But GET parameters don't go in the body, they go right on the URL. So your first example is simply making a GET request to the base URL with no parameters at all. Note also that the method parameter already defaults to GET, so you can just skip the whole streams bit.

    You can build your URL like:

    $urlBase = 'https://login.microsoftonline.com/common/adminconsent';
    $data = [
        'client_id' => '...',
        'state' => '12345',
        'redirect_uri' => 'http://localhost/myapp/permissions',
    ];
    $url = $urlBase . '?' . http_build_query($data);
    

    And then just:

    $content = file_get_contents($url);
    

    Or just cram it all into one statement:

    $content = file_get_contents(
        'https://login.microsoftonline.com/common/adminconsent?' .
        http_build_query([
            'client_id' => '...',
            'state' => '12345',
            'redirect_uri' => 'http://localhost/myapp/permissions',
        ])
    );
    

    Or use $url to feed curl_init() or Guzzle or similar.