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

DDD
發布: 2024-10-18 08:44:03
原創
472 人瀏覽過

How to Send Multiple Cookies with file_get_contents in PHP?

Sending Multiple Cookies with file_get_contents

The PHP manual provides an example demonstrating how to send a cookie using stream contexts. However, it does not address the scenario of sending multiple cookies.

Multiple Cookie Options

There are several options for sending multiple cookies:

  • Option 1:
<code class="php">"Cookie: user=3345&pass=abcd\r\n"</code>
登入後複製

This option combines the cookies into a single string, separated by an ampersand (&). However, it may not be compatible with all servers.

  • Option 2:
<code class="php">"Cookie: user=3345\r\n" . 
"Cookie: pass=abcd\r\n"</code>
登入後複製

This option sends the cookies as separate lines with individual Cookie headers. It provides better compatibility but may look messy.

Optimal Solution

The preferred option for sending multiple cookies is:

  • Option 3:
<code class="php">Cookie: user=3345; pass=abcd</code>
登入後複製

This syntax uses semicolons (;) to separate the cookie pairs. It is widely supported and follows the HTTP cookie specification.

Implementation

To send multiple cookies using file_get_contents:

<code class="php">$cookies = array('user' =&gt; '3345', 'pass' =&gt; 'abcd');
$cookieString = '';
foreach ($cookies as $name =&gt; $value) {
    $cookieString .= "$name=$value;";
}

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

$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);</code>
登入後複製

以上是如何在 PHP 中使用 file_get_contents 傳送多個 Cookie?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!