Monday, 13 June 2011

PHP COOKIES HANDLING - USING COOKIES IN PHP




How cookies work in PHP


We have just seen that the PHP session id is by default passed through the cookies. But what are cookies exactly ? 
  • Cookies are elements which allow a website to leave some information on a visitor's computer for a given period of time and access it at a later time when the visitor comes back to the website (even days, weeks or months after his last session was ended).
  • Cookies are managed at the level of the internet browser (i.e., the cookies made available to a browser will be treated independently from the cookies made available to another browser, if you happen to run two different internet browsers on your computer). In particular, it is possible to disable cookies on a browser, and people who do so won't be able to accept cookies from websites (actually, there exist different levels of permissions, but we won't enter such a level of details here).
  • Cookies are very useful, for instance in the case of authentication protocols when you want to "remember" a user, i.e. to keep him logged in for a given period of time even when his session is terminated, in order to save him the trouble of having to re-enter his username and password multiple times.
  • Creating a cookie in PHP

    In order to create a cookie in PHP, you must use the function setcookie(); the PHP syntax to follow is:

    setcookie(name_of_cookie, value_of_cookie, expiration_time),
    • where name_of_cookie is a string which indentifies the cookie
    • where value_of_cookie is the value of this cookie (also a string)
    • where expiration_time is the time at which the cookie will expire (i.e., is destroyed in the visitor's browser); this time is expressed in number of seconds from the current time (you can for instance decide that cookie will expire in one hour by using time()+3600).
  • eading a cookie in PHP

    Once a cookie has been set, you need to be able to retrieve it. You can do so by using the superglobal variable $_COOKIE, which is an array whose indexes (keys) are the cookies' names.

    Checking whether a cookie has been set

    In order to ascertain the existence of a cookie in PHP, you can use the expression isset($_COOKIE[name_of_cookie]) which returns TRUE if the cookie has been set, FALSE otherwise.

    Destroying a cookie in PHP
    In order to destroy a cookie in PHP, all you have to do is set his expiration time to the past; for instance, you could use the PHP syntax:

    setcookie(name_of_cookie, value_of_cookie, time()-1)

    The following example sets a cookie, checks that it has been set, retrieves it and then prints its value in the visitor's browser:

    Learn the PHP code:
    <?php
    setcookie('cookie1','this is my cookie', time() + 3600);
    // After the page has been reloaded if (isset($_COOKIE['cookie1']))
    echo 'The cookie has been set'.'<br>'
    echo 'Its value is "'.$_COOKIE['cookie1'].'"<br>';
    ?>

    Run the PHP script in your web browser

    Set a cookie in PHP with setcookie()
    Remark:

    Once a cookie is set, the page must be reloaded in order for the cookie to be retrieved. The same remark applies for the destruction of cookies: until the page is reloaded in the browser, the superglobal variable $_COOKIE['cookie1'] remains available.
    Reload the page in your web browser:

    Setting cookies with the PHP function setcookie()

    Security issues: cookies used in PHP authentication protocols
    Very often, you might want to allow a user to remain logged in for a certain number of time (in weeks or months ...). In order to achieve this, you must be able to set a cookie which will contain:
    • the identity of this user (his username, for instance)
    • a way to verify that this user has the rights to log into the requested account

    In order to achieve the last point, you might be tempted to store this user's password and compare it to the corresponding data in your MySQL database. The problem with this approach is that the cookie on your visitor's machine might be intercepted and read by an adverse party, who will thus gain unauthorized access to the account of your visitor.

    A way to remedy this problem is to encrypt the data stored in your cookie so that if it is intercepted by another party, it won't be decipherable. It is easy enough to achieve this using any encryption method of your choice, the idea being that PHP script will uncrypt that cookie and then compare the user's password with the information stored in your database.

    However, that method, though significantly better than the previous one, is still not that satisfactory: indeed, if someone came to steal your server's database, this person would automatically collect all of your users' usernames and passwords. In order to remedy this problem, you might want to encrypt the passwords in your database as well, and uncrypt them only at the moment of the authentication. Well, this is not really solving our problem: indeed, if you still need to uncrypt the password on both sides (that stored in the database and that stored within the cookie), then at one moment or another the key to decypher the information must appear in your script, and anyone who would be able to steal the source code of your script would also get access to these passwords. So, what could be a more acceptable solution ?

    The best solution would be that you encrypt the information both in your MySQL database and within your user's cookies, while at no time needing to uncrypt that information. In particular, you wouldn't even be able to uncrypt it yourself, which means that absolutely noone would be able to gain unauthorized access to your users' passwords, not even yourself -the owner of the server (this is of course assuming that your encryption method is reliable enough). The key of this method lies in the fact that if the password provided is the right one, then its encrypted version within the cookie and that stored in your database should be rigorously the same.

    However, how is that possible to come up with a method to reliably encrypt a password without being able to uncrypt it afterwards (even while knowing which encryption method was used) ? One solution is to devise an encryption method so that the way the data is encrypted depends on the data itself ... in this way, given a password, you know how to encrypt it (since you hold the encryption method and the password, i.e. the data, which you are not supposed to know) but once the password is encrypted, you have no way to decipher it (because you do not know how it was encrypted since the encryption method depended on the data to be encrypted).
    Practically, the PHP language proposes you to achieve such a one-way encryption by using the crypt() function.
    PHP cookies allow you to store information about your visitor on his own computer and to access it later (even a long time after his PHP session was ended).
    You can use cookies for several purposes; for instance, cookies can help you to implement authentication methods. They can also allow you to store a user's navigation preferences or its commercial profile without having to store those on your server's web database.

No comments:

Post a Comment