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.
content
參數(shù)用于請求正文,適用于 POST 和 PUT 請求。但 GET 參數(shù)不會出現(xiàn)在正文中,而是直接出現(xiàn)在 URL 中。因此,您的第一個示例只是向基本 URL 發(fā)出 GET 請求,根本不帶任何參數(shù)。另請注意,method
參數(shù)已默認(rèn)為 GET,因此您可以跳過整個流位。
您可以像這樣構(gòu)建 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);
或者只是將所有內(nèi)容塞進(jìn)一個語句中:
$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或類似的。