Cookies and Sessions in PHP

PHP

Cookies are used to store values and information. They are stored by the browser on the client’s side. So you can access cookies from multiple pages of your website. When they are stored, the data is URLencoded and they are decoded during retrieval. While setting a cookie, you can set a name, value, expiration date and other additional details like path and domain. Cookies must be set before anything is printed. So, create cookies before any HTML or echo codes.

Setting Cookies

Here is how you set a cookie:

<?php
$cookiename = "Address";
$cookievalue = "Kathmandu";
setcookie ($cookiename, $cookievalue, time()+86400);
?>
Note: The cookie set above will expire after 86400 seconds i.e. one day.

Retrieving Cookies

Cookies can be retrieved from other pages of the same website. Here’s how you retrieve the cookie set above

<?php
echo $_COOKIE["Address"];
?>
Output:
Kathmandu
Notes:

  • The PHP codes can be in the same as well as different file.
  • All the cookies set by your website can be access by using print_r($_COOKIE);

Deleting Cookies

If you want to remove cookies set by your script, you will have to expire them. Just set their expiration date in the past. This will trigger the browser’s cleaning mechanism and will remove the cookie.

Example:

<?php
setcookie($cookiename, "", time()-3600);
?>

Sessions

Sessions are similar to functionality when compared to cookies. They store values which can be used in multiple PHP pages. But, they are not stored in the user’s browser. This makes it more secure. Sessions should also be started before anything is outputted on the browser. That means you have to place session_start() before anything else.

Starting Sessions

<?php
session_start();
$_SESSION["name"]="Ashish";
?>

Accessing Sessions

You can access the PHP sessions from any page.

Example:

<?php
echo $_SESSION["name"];
?>
Output:
Ashish
Notes:

  • To show all the sessions set, use print_r($_SESSIONS);
  • You can modify the session variables just like you’d modify any other PHP variables.

Destroying Sessions

When you need to remove sessions completely, you will have to unset and destroy them.

Example:

<?php
session_unset();
session_destroy();
?>