"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Send Multiple Cookies with file_get_contents in PHP?

How to Send Multiple Cookies with file_get_contents in PHP?

Published on 2024-10-31
Browse:372

How to Send Multiple Cookies with file_get_contents in 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:

  • Option 1:
"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.

  • Option 2:
"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:

  • Option 3:
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);
Release Statement This article is reprinted at: 1729212137 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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