PHP-HTTP-Anfrage ignoriert Parameter
P粉765570115
P粉765570115 2024-04-05 10:54:48
0
1
3540

Bevor ich anfange zu fragen, sollte ich erwähnen, dass ich PHP nach langer Zeit wieder neu lerne. Bitte sei höflich. Ich weiß auch, dass ich für einige dieser Dinge Bibliotheken wie Curl verwenden kann, aber ich möchte verstehen, wie PHP selbst funktioniert.

Ich versuche, eine http-GET-Anfrage an die Microsoft API (Identity Platform) zu senden. Hier ist mein 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;
?>

Wenn ich versuche, den obigen Code auszuführen, erhalte ich: Fehlerausschnitt

Stattdessen funktioniert die http-Anfrage mit dem folgenden Code einwandfrei:

<?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;
?>

Kann jemand einen Einblick geben, warum das erste Beispiel fehlschlägt und das zweite Beispiel erfolgreich ist? Meiner Meinung nach muss es einen Syntaxfehler geben. Dank im Voraus.

P粉765570115
P粉765570115

Antworte allen(1)
P粉827121558

content 参数用于请求正文,适用于 POST 和 PUT 请求。但 GET 参数不会出现在正文中,而是直接出现在 URL 中。因此,您的第一个示例只是向基本 URL 发出 GET 请求,根本不带任何参数。另请注意,method 参数已默认为 GET,因此您可以跳过整个流位。

您可以像这样构建 URL:

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

然后就是:

$content = file_get_contents($url);

或者只是将所有内容塞进一个语句中:

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

或者使用$url来提供curl_init()或Guzzle或类似的。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!