0
Posted December 2, 2012 by Victor in PHP Programming
 
 

How to Set up and Use Cookies in PHP

cookies
cookies

Do you know how to set cookies in PhP? If you have not, then, you have to know that they are a manner in which data which tracks or identifies returning users is stored on the remote browser of the said user. If you have used PhP server side scripting, then, you probably have heard of PhP Cookies.

A cookie is meant to identify a user and is known as a small file embedded on the user’s computer. The computer which will remember the user’s information each time the user requests a web page he had previously visited. PhP gives you the power to create and retrieve cookies.

Why are PhP Cookies Used?

To help you better understand cookies, you will need to know their usage. The most important reasons why cookies exist are:

  1. They are used to store information about the username and password information. This means that the user will not need to remember his information every time he signs in to your website. PhP Cookies come with words like “remember me” tab when you are signing in.
  2. PhP Cookies can be set so as to remember the name of the website user so that the next time he comes to the same site, he is addressed by his name.
  3. Cookies can be used for keeping track of someone’s progress in a given web process. For instance, when someone was creating a new account or filling a marketing survey online.
  4. PhP Cookies can help in remembering what the user preferred and restoring what the user was doing on your website before he logged off.

Setting up PhP Cookies

Setting up a PhP cookie will need the use of either the setcookie() or the setrawcookie() PhP functions. Since cookies are often set on the HTTP header, they have to be called before an output goes to the browser.

When using the setcookie () function, there are three arguments that will have to be specified within the function. These are setcookie (name, value, expiration, domain):

  1. Name: This is the name of the cookie you are setting up. The name is important because it will help the user retrieve the cookie.
  2. Value: These are the values which are stored in the cookie and may include values such as the usernames or the specifics on the exact time of a person’s visit to your website.
  3. Expiration: This is simple the date and time when the cookie is set to expire and when the said cookie will be deleted. When the expiration time is not set, the cookie is removed when the browsing session ends and the browser is restarted (known as a session cookie).
  4. Domain: This will be the domain name from which the cookie originates from.

Here is a simple example of how cookies are set:


<html>

<body>

<?php
     setcookie("login", "victor", time()+ 60*60*24*365);

     /* The cookie time is one year and is measured as sixty multiplied by sixty to get 3600 seconds
        in an hour multiplied by 24 hours multiplied by the number of days in a year (365) */
?>
</body>
 <html>

There are other things you need to know about cookies is that despite the fact that they have an expiration date, a user will be in a position to delete the cookie before it expires. Also, cookies will only be accessible to browsers that they are set in because browsers such as Internet explore and Firefox do not share cookies. A user also has the option of turning off cookies.

A working example of how cookies are used is highlighted here below:


<html>
<head>
<title>vic.php</title>
</head>
<body>

 <?php
      /* This is my valid username and password that I enter in the login form */
      $user = 'victor';
      $pass = 'mypassword';

     /* This gets my information from the login form and verifies the information against the
        information stored in $user and $pass*/

     if (isset($_POST['username']) && isset($_POST['password'))
     {
        if (($_POST['username'] == $user) && ($_POST['password'] == $pass))
        {
            if (isset($_POST['remembermeonthiscomputer']))
            /* the cookies work only if someone checks this option on the html form*/
            {
                /* If all the above conditions are true the codes below now sets the cookies for two years for both
                the username and password*/
                setcookie('username', $_POST['username'], time()+60*60*24*365*2, '/account', 'www.victor.com');
                setcookie('password', md5($_POST['password']), time()+60*60*24*365*2, '/account', 'www.victor.com');
            }
            else /* If the conditions are not true*/
            {
                /* the Cookie will expire when the browser closes */
                setcookie('username', $_POST['username'], false, '/account', 'www.victor.com');
                setcookie('password', md5($_POST['password']), false, '/account', 'www.victor.com');
            }

            /* this now sets the cookies to the header section of your index page*/
            header('Location: index.php');
         }
         /* this is when someone enters the wrong username or password*/
         else
             echo 'Invalid Password or Username';
     }
     /* this is when someone leaves the form for username or password blank*/
     else
         echo 'Please enter your username and password.';
 ?>
</body>
</html>


Victor