ホームページ  >  記事  >  バックエンド開発  >  file_get_contents() を使用して複数の Cookie を送信するにはどうすればよいですか?

file_get_contents() を使用して複数の Cookie を送信するにはどうすればよいですか?

Susan Sarandon
Susan Sarandonオリジナル
2024-10-18 08:40:29728ブラウズ

How Do I Send Multiple Cookies with file_get_contents()?

file_get_contents() を使用した複数の Cookie の送信

PHP マニュアルでは、file_get_contents() でストリーム コンテキストを使用して Cookie を送信する方法を示しています。ただし、この例では 1 つの Cookie を送信する方法のみを示しています。この記事では、このメソッドを使用して複数の Cookie を送信する方法について説明します。

次のコードを考えてみましょう。

<code class="php">// Create a stream
$opts = array(
  'http' => array(
    'method' => "GET",
    'header' => "Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);</code>

このコードは、値「bar」を持つ「foo」という名前の 1 つの Cookie を送信します。複数の Cookie を送信するには、次の方法を使用できます:

オプション 1: ; を使用します。 Cookie ペアを単一の「Cookie」ヘッダーに結合する区切り文字。

<code class="php">$opts['http']['header'] .= "Cookie: user=3345; pass=abcd\r\n";</code>

オプション 2: Cookie ごとに個別の「Cookie」ヘッダーを送信します。

<code class="php">$opts['http']['header'] .= "Cookie: user=3345\r\nCookie: pass=abcd\r\n";</code>

オプション 3 (推奨): ; を使用します。セパレータを使用して、複数の Cookie ペアを 1 つの「Cookie」ヘッダーに結合します。ただし、読みやすくするために、各 Cookie ペアをスペースで区切ってください。

<code class="php">$opts['http']['header'] .= "Cookie: user=3345; pass=abcd\n";</code>

以上がfile_get_contents() を使用して複数の Cookie を送信するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。