How Do I Send Multiple Cookies with file_get_contents()?

Susan Sarandon
Release: 2024-10-18 08:40:29
Original
726 people have browsed it

How Do I Send Multiple Cookies with file_get_contents()?

Sending Multiple Cookies with file_get_contents()

The PHP manual demonstrates how to send cookies using stream contexts with file_get_contents(). However, the example only shows how to send a single cookie. This article explores how to send multiple cookies using this method.

Consider the following code:

<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>
Copy after login

This code sends a single cookie named "foo" with the value "bar". To send multiple cookies, you can use the following approaches:

Option 1: Use the ; separator to combine cookie pairs into a single "Cookie" header.

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

Option 2: Send separate "Cookie" headers for each cookie.

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

Option 3 (Recommended): Use the ; separator to combine multiple cookie pairs into a single "Cookie" header. However, separate each cookie pair with a space to improve readability.

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

The above is the detailed content of How Do I Send Multiple Cookies with file_get_contents()?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!