Cookies Encoded during Transportation in PHP


How Are Cookies Encoded During Transportation in PHP?



When cookies are transported from servers to browsers and from browsers back to servers, Cookies values are always encoded using the URL encoding standard to ensure that they are transported accurately. But you don't need to worry about the encoding and decoding processes yourself. PHP engine will automatically encode cookies created by setcookie(), and decode cookies in the $_COOKIE array. The tutorial exercise will help you understand this concept better.

Write a sample PHP script, encoding_cookies.php, like this:

  setcookie("Letters", "FYICenter");
  setcookie("Symbols", "A~!@#%^&*(), -_=+[]{};:'\"/?<>.");
  setcookie("Latin1", "\xE6\xE7\xE8\xE9\xA5\xA9\xF7\xFC");
  $count = count($_COOKIE);
  print("$count cookies received.\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";

First, run this script off-line in a command window:

>php-cgi encoding_cookies.php
Content-type: text/html
X-Powered-By: PHP/5.0.4
Set-Cookie: Letters=FYICenter
Set-Cookie: Symbols=A%7E%21%40%23%25%5E%26%2A%28%29%2C
Set-Cookie: Latin1=%E6%E7%E8%E9%A5%A9%F7%FC

0 cookies received.

You see how cookie values are encoded now. Then copy the script, encoding_cookies.php to the Web server, and run it with a browser. You will get:

3 cookies received.
  Letters = FYICenter
  Symbols = A~!@#%^&*(), -_=+[]{};:\'\"/?.<>
  Latin1 = 稨饩󼍊

This shows that the values in the $_COOKIE array are already decoded.


Understanding and Managing Cookies in PHP

⇒⇒PHP Tutorials

2016-10-29, 223👍, 0💬