Bagaimana untuk Menghantar Berbilang Kuki dengan file_get_contents dalam PHP?

DDD
Lepaskan: 2024-10-18 08:44:03
asal
546 orang telah melayarinya

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:
<code class="php">"Cookie: user=3345&pass=abcd\r\n"</code>
Salin selepas log masuk

This option combines the cookies into a single string, separated by an ampersand (&). However, it may not be compatible with all servers.

  • Option 2:
<code class="php">"Cookie: user=3345\r\n" . 
"Cookie: pass=abcd\r\n"</code>
Salin selepas log masuk

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:
<code class="php">Cookie: user=3345; pass=abcd</code>
Salin selepas log masuk

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' =&gt; '3345', 'pass' =&gt; 'abcd');
$cookieString = '';
foreach ($cookies as $name =&gt; $value) {
    $cookieString .= "$name=$value;";
}

$opts = array(
  'http' =&gt; array(
    'method' =&gt; 'GET',
    'header' =&gt; "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>
Salin selepas log masuk

Atas ialah kandungan terperinci Bagaimana untuk Menghantar Berbilang Kuki dengan file_get_contents dalam PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan