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>
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>
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>
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>
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!