Maison > Article > développement back-end > Comment envoyer plusieurs cookies avec file_get_contents en 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:
<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.
<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:
<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' => '3345', 'pass' => 'abcd'); $cookieString = ''; foreach ($cookies as $name => $value) { $cookieString .= "$name=$value;"; } $opts = array( 'http' => array( 'method' => 'GET', 'header' => "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>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!