在開(kāi)始提問(wèn)之前,我要提到的是,在離開(kāi) PHP 很長(zhǎng)一段時(shí)間後,我正在重新學(xué)習(xí) PHP。請(qǐng)溫柔一點(diǎn)。另外,我知道我可以使用像curl 這樣的函式庫(kù)來(lái)完成其中一些事情,但我想了解PHP 本身是如何運(yùn)作的。
我正在嘗試向 Microsoft API(身分平臺(tái))提交 http GET 請(qǐng)求。以下是我的程式碼:
<?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í)行上面的程式碼時(shí),我得到: 錯(cuò)誤片段
相反,使用以下程式碼,http 請(qǐng)求工作正常:
<?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)為什麼第一個(gè)範(fàn)例失敗而第二個(gè)範(fàn)例成功的見(jiàn)解嗎?我的想法是一定存在某種語(yǔ)法錯(cuò)誤。提前致謝。
content
參數(shù)用於請(qǐng)求主體,適用於 POST 和 PUT 請(qǐng)求。但 GET 參數(shù)不會(huì)出現(xiàn)在正文中,而是直接出現(xiàn)在 URL 中。因此,您的第一個(gè)範(fàn)例只是向基本 URL 發(fā)出 GET 請(qǐng)求,完全不帶任何參數(shù)。另請(qǐng)注意,method
參數(shù)已預(yù)設(shè)為 GET,因此您可以跳過(guò)整個(gè)流位。
您可以像這樣建立 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)一個(gè)語(yǔ)句中:
$content = file_get_contents( 'https://login.microsoftonline.com/common/adminconsent?' . http_build_query([ 'client_id' => '...', 'state' => '12345', 'redirect_uri' => 'http://localhost/myapp/permissions', ]) );
或使用$url
來(lái)提供curl_init()
或Guzzle或類(lèi)似的。