Cookies and Sessions in 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:

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

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:

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

Accessing Sessions

You can access the PHP sessions from any page.

Example:

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:

You may also like

Comments are closed here.

Advertisements

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers