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:
"Cookie: user=3345&pass=abcd\r\n"
This option combines the cookies into a single string, separated by an ampersand (&). However, it may not be compatible with all servers.
"Cookie: user=3345\r\n" .
"Cookie: pass=abcd\r\n"
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:
Cookie: user=3345; pass=abcd
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:
$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);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3