Course Banner


PHP Cookies

What is Cookie?

Cookies are nothing but text files which are created and stored on client's computer. First, cookies files are create and then the same file information is accessed and action is performed as per the information. Cookies require three steps to perform the task.

  • ● Cookie is not created automatically on client's computer, its server's script which commands to the web browser to create the file.
  • ● Browser stores the information on client's local computer.
  • ● When browser sends information to web server, it first reads cookie file and sends required information to server. Server programming language reads the information and performs the task.

HOW TO SET COOKIE

There is special function in PHP for storing and retrieving the information. To set the cookie, we can use setcookie() function. This setkookie() functions requires parameters. Few are compulsory and few are optional. Here is the detail of all the arguments:

  • ● Name : The first argument for cookie is name of the cookie. And its mandatory argument. The environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • ● Value : After cookie name, the next mandatory parameter for this is 'value'. Value is in fact the actual data which we store in cookie.
  • ● Expiry : Once the cookie information is stored on computer, it's not that we are going to use that forever. For security reason its best to give time-frame and then it will expire after certain time. In expiry parameter, we set time. And up to that time the information will be available and after that it will get expired.
  • ● Path : Path tells the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • ● Domain : We can also define domain name for which the cookie will be available. This is good because there can be same cookie name but domain name is different . On the basis of domain name we can access same name cookie based on domain name.
  • ● Security : In this it specifies if the cookie information will be sent and accessed using secure connection (https) or insecure connection (http). For Https we use 1 and for non-secure we use 0.

Example :

democookie.php

< html>
< head>
< title>Setting Cookies with PHP< /title>
< /head>
< body>

<?php
  1. setcookie("full_name", "Rajesh Das", time()+3600, "/","", 0);
  2. setcookie("roll_no", "36", time()+3600, "/", "", 0);
  3. ?>

< /body>
< /html>

Open this page in the browser. Though it will not show anything but you can check cookie from console.


Now, press F12 in chrome and then you can see the cookie.


Open Application tab and then click on cookies and then you can see the cookie set in your coputer.

RETRIEVE COOKIE Accessing Cookies with PHP In php we can use more than one ways to access stored value of cookie. One of the easiest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

cookie_access.php

< html>
< head>
< title>Accessing Cookies with PHP< /title>
< /head>
< body>

<?php
  1. error_reporting(E_ERROR);
  2.       echo$_COOKIE["full_name"]. " ";
  3. /* is equivalent to */
  4.       echo$HTTP_COOKIE_VARS["full_name"]. " ";
  5.       echo$_COOKIE["roll_no"] . " ";
  6. /* is equivalent to */
  7.       echo$HTTP_COOKIE_VARS["roll_no "] . " ";
  8. ?>

< /body>
< /html>

And the output will be:


We can use isset() function to check if a cookie is set or not.

< html>
< head>
< title>Accessing Cookies with PHP< /title>
< /head>
< body>

<?php
  1. if( isset($_COOKIE["full_name"]))
  2.       echo"Welcome " . $_COOKIE["full_name"] . " ";
  3. else
  4.       echo"Sorry... Not recognized" . " ";
  5. ?>

< /body>
< /html>

Deleting Cookie with PHP Generally the cookie is deleted with calling setcookie() with the name argument only but this does not always work well, however, and should not be relied on. It is safest to set the cookie with a date that has already expired:

delete_cookie.php

< html>
< head>
< title>Deleting Cookies with PHP< /title>
< /head>
< body>

<?php
  1. setcookie( "full_name", "", time()- 60, "/","", 0);
  2. setcookie( "roll_no", "", time()- 60, "/","", 0);
  3. ?>
  4. echo"Deleted Cookies"?>

< /body>
< /html>

LOGIN WITH COOKIES

In this section of tutorial we will see practical example of Cookies use with PHP in our login system. Before you proceed ahead with this system, I strongly recommend to cover 'Login with PHP' in PHP SESSSION section. Because here I have modified the existing login code and added cookie code. So, lets open login.php page and make the changes below. I am keeping this file separate so that you can compare the code and see the difference.

login-with-cookie.php

(save the file inside admin folder)

<?php
  1. session_start();
  2. error_reporting(E_ERROR);
  3. /* mysql connection code here */
  4. include('../db_connect.php');
  5. /*IF YOU OPEN LOGIN PAGE, IT WILL FIRST CHECK IF THE COOKIE IS SET. IF YES THEN REDIRECT TO INDEX.PHP PAGE*/
  6. if($_COOKIE['user_name']!=''){
  7. header('Location:register_list.php');
  8. }
  9. if($_POST){
  10. $sel="SELECT*FROMadminWHEREuser_name='".
    $
    _POST['
    user_name<span class="dbl-quot">']."'
  11. AND password ='".$_POST['password<span class="dbl-quot">']."'";
  12. $qry=mysqli_query($conn,$sel);
  13. $nums=mysqli_num_rows($qry);
  14. if($nums>0){
  15. $_SESSION['user_name']= $_POST['user_name'];
  16. if($_POST['remeber']=='yes'){
  17. setcookie("user_name", $_POST['user_name'], time()+3600*24*15); /* expire in 15 days */
  18. }
  19. header('Location:register_list.php');
  20. }
  21. else{
  22.       echo"Sorry invalid user or passsword";
  23. }
  24. }
  25. ?>

< html>
< head>
< title>Login Page< /title>
< /head>
< body>
< h2>Login Page< /h2>
< ?php echo$invalid?>
< form method="post"action="">
Email Id : < input type="text" name="user_name" placeholder="Enter User Id">< br>
Password : < input type="password" name="password" placeholder="Enter Password">< br>
Remeber me : < input type="checkbox" name="remeber" value="yes">< br>
< input type="submit" name="submit" value="Please Login">
< /form>
< /body>
< /html>

Also make changes in auth.php file.So, our file will look like below.

<?php
  1. session_start();
  2. if($_SESSION['user_name']==' ' or $_COOKIE['user_name']==''){
  3. header('Location:login.php');
  4. }
  5. ?>