Sunday, September 27, 2020

PHP Cookies with Examples



Hello, dear readers! welcome back to another section of my tutorial on PHP. In this tutorial guide, we will be studying about Cookies in PHP.

Cookies are text files stored in the client machine and they are kept for tracking purpose. PHP clearly have support for HTTP cookies.

There are three key steps used for identifying returning users -

  • Server script sends a set of cookies to the browser. For example name, age or sex.
  • The browser stores this data on local machine for future use.
  • When next the web browser sends a request to the web server, then it sends those cookies data to the server and server uses that data to identify the user.

In this tutorial, i will be giving a detailed explanation on how to set cookies, access the cookies, and lastly how to delete them.

RECOMMENDED POST: PHP Functions

The Anatomy of a Cookie

Cookies are mostly set in an HTTP header. A PHP script that sets a cookie might send some headers that look like this -

HTTP/1.1 200 OK
Date: Sun, 27 Sep 2020 11:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Sunday, 27-Sep-23 22:03:38 GMT; 
                 path=/; domain=webdesigntutorialz.com
Connection: close
Content-Type: text/html

Here, the set-Cookie header holds a name value pair, a GMT date, a path and a domain. The name and the value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookies after the given time and date.

If the web browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the web browser at any web page which matches the path and domain of the cookie, it will resend the cookies to the web server. The browser headers might look like this -

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz

A PHP script will then have access to the cookies in the environment variables which contains all the cookie names and values.

RECOMMENDED POST: PHP File Handling (I/O)


Setting Cookies with PHP

PHP provides a function known as setcookie() used to set a cookie. This function requires up to six arguments and should be called before <html> tag. For each cookie that you want to set, this function should be called separately.

setcookie(name, value, expire, path, domain, security);

Parameter Details

Following below is the details of all the arguments -

  • Name - This sets the name of the cookie and is stored in the environmental variable called HTTP_COOKIES_VAR. This variable is used while accessing cookies.
  • Value - This sets the value of the name variable and is the content that you actually want to store.
  • Expiry - This specify a future time in secs since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If you do not set this parameter then the cookie will expire once the web browser is closed.
  • Path - The path argument is used to specify the directory for which the cookie is valid. A single "/" character allows the cookie to be valid for all directorie.
  • Domain - This can be used to specify the domain name in very large domains and then contain at least two periods to be valid. All cookies can only be valid for the host & domain which created them.
  • Security - This can be set to 1 to specify that the cookie should only be sent through secure transmissions using HTTPS else set to 0, which means that the cookie can be sent via regular HTTP.

Example

The following example is going to create two cookies name and age. These cookies will expire after two hours.

<?php
   setcookie("name", "Precious Amah", time()+7200, "/","", 0);
   setcookie("age", "25", time()+7200, "/", "",  0);
?>
<html>
   
   <head>
      <title>Setting Cookies with PHP</title>
   </head>
   
   <body>
      <?php echo "Set Cookies"?>
   </body>
   
</html>



Accessing Cookies with PHP

PHP provides various methods of accessing cookies. The simplest method is by using $_COOKIE or $HTTP_COOKIE_VARS variables to access the cookies.

Example

The following example will access all the cookies set in the above examples -

<html>
   
   <head>
      <title>Accessing Cookies with PHP</title>
   </head>
   
   <body>
      
      <?php
         echo $_COOKIE["name"]. "<br />";
         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["name"]. "<br />";
         
         echo $_COOKIE["age"] . "<br />";
         
         /* is equivalent to */
         echo $HTTP_COOKIE_VARS["age"] . "<br />";
      ?>
      
   </body>
</html>

You can use the Isset() function to check if a cookie is set or not.

<html>
   
   <head>
      <title>Accessing Cookies with PHP</title>
   </head>
   
   <body>
      
      <?php
         if( isset($_COOKIE["name"]))
            echo "Welcome " . $_COOKIE["name"] . "<br />";
         
         else
            echo "Sorry... Not recognized" . "<br />";
      ?>
      
   </body>
</html>

RECOMMENDED: Loops in PHP


Deleting Cookies with PHP
To delete a cookie, you should call setcookie() function with the name argument only but this does not always work well, and should not be relied on.

It's safest to set the cookie with a date that has already expired -

<?php
   setcookie( "name", "", time()- 70, "/","", 0);
   setcookie( "age", "", time()- 70, "/","", 0);
?>
<html>
   
   <head>
      <title>Deleting Cookies with PHP</title>
   </head>
   
   <body>
      <?php echo "Deleted Cookies" ?>
   </body>
   
</html>

RECOMMENDED POST: PHP Comparison Operators

Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial post, we will be discussing about PHP Sessions. 

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.