PHP HTTP request ignores parameters
P粉765570115
P粉765570115 2024-04-05 10:54:48
0
1
3713

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.

P粉765570115
P粉765570115

reply all(1)
P粉827121558

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 the method parameter already defaults to GET, so you can skip the whole stream bit.

You can build the URL like this:

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

Then:

$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 provide curl_init() or Guzzle or similar.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template