首页  >  文章  >  后端开发  >  如何使用 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。但是,该示例仅显示如何发送单个 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>

此代码发送一个名为“foo”、值为“bar”的 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 对组合成一个“Cookie”标头。但是,请用空格分隔每个 cookie 对以提高可读性。

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

以上是如何使用 file_get_contents() 发送多个 Cookie?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn