在開始提問之前,我要提到的是,在離開 PHP 很長一段時間后,我正在重新學(xué)習(xí) PHP。請溫柔一點。另外,我知道我可以使用像curl 這樣的庫來完成其中一些事情,但我想了解PHP 本身是如何工作的。
我正在嘗試向 Microsoft API(身份平臺)提交 http GET 請求。以下是我的代碼:
<?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; ?>
當(dāng)我嘗試執(zhí)行上面的代碼時,我得到: 錯誤片段
相反,使用以下代碼,http 請求工作正常:
<?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; ?>
任何人都可以提供有關(guān)為什么第一個示例失敗而第二個示例成功的見解嗎?我的想法是一定存在某種語法錯誤。提前致謝。
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或類似的。