」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 PHP 中使用 file_get_contents 傳送多個 Cookie?

如何在 PHP 中使用 file_get_contents 傳送多個 Cookie?

發佈於2024-10-31
瀏覽:126

How to Send Multiple Cookies with file_get_contents in PHP?

使用 file_get_contents 發送多個 Cookies

PHP 手冊提供了一個範例,示範如何使用串流上下文發送 cookie。但是,它沒有解決發送多個 cookie 的場景。

多個Cookie 選項

發送多個cookie 有以下幾個選項:

  • 選項1:
"Cookie: user=3345&pass=abcd\r\n"

此選項將Cookie 合併為一個字串,由與號(&) 分隔。但是,它可能並不與所有伺服器相容。

  • 選項 2:
"Cookie: user=3345\r\n" . 
"Cookie: pass=abcd\r\n"

此選項將 cookie 以單獨 Cookie 標頭的單獨行傳送。它提供了更好的兼容性,但可能看起來很混亂。

最佳解決方案

發送多個cookie的首選選項是:

  • 選項3:
Cookie: user=3345; pass=abcd

此語法使用分號(;) 分隔cookie 對。它受到廣泛支持,並遵循 HTTP cookie 規範。

實作

使用file_get_contents 傳送多個cookie:

$cookies = array('user' => '3345', 'pass' => 'abcd');
$cookieString = '';
foreach ($cookies as $name => $value) {
    $cookieString .= "$name=$value;";
}

$opts = array(
  'http' => array(
    'method' => 'GET',
    'header' => "Accept-language: en\r\n" .
              "Cookie: $cookieString\r\n"
  )
);

$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);
版本聲明 本文轉載於:1729212137如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3