How PHP sessions work
PHP sessions allow you to keep information about a visitor as he browses your website; indeed, as soon as your visitor leaves a page and opens another, a system must exist which allows you to keep track of the inputs/parameters associated with that user.
When the visitor leaves your website and terminates his internet session, his PHP session is destroyed and all the information associated with that user is lost; therefore, if you want to store this information permanently, you must do so in a database. Indeed, the purpose of a session is only to allow the transmission of the information from one page to another during all the time that a visitor visits your website (and even more, during all the time that his current internet session is maintained), and not to store this information permanently on your server. Imagine for instance a visitor who is playing games on your website and needs to navigate several pages; you need to preserve this visitor's information during all the game(s) but you don't need to specifically store such information for later use because it has no value for you -the webmaster-. PHP sessions are there to help you achieve this.
When the visitor leaves your website and terminates his internet session, his PHP session is destroyed and all the information associated with that user is lost; therefore, if you want to store this information permanently, you must do so in a database. Indeed, the purpose of a session is only to allow the transmission of the information from one page to another during all the time that a visitor visits your website (and even more, during all the time that his current internet session is maintained), and not to store this information permanently on your server. Imagine for instance a visitor who is playing games on your website and needs to navigate several pages; you need to preserve this visitor's information during all the game(s) but you don't need to specifically store such information for later use because it has no value for you -the webmaster-. PHP sessions are there to help you achieve this.
Starting a PHP session
You can start a PHP session with the PHP command session_start(), which must be placed before the <html> tag. When you start a PHP session, a unique user ID is attributed in order to identify the PHP session (until it terminates when the visitor leaves your website or when you destroy it).
Remark:
The command session_start() must be called on each page where you want the session information to be transmitted.
If your visitor is redirected towards a page on which the session_start() was omitted, the information relative to his current session won't be made available on this page (nor will it be possible to change them or add any extra input). However, the session still exists and can be resumed on another page by calling session_start() again. If however the visitor closes his internet session (i.e. closes his session in the browser), his PHP session will be lost.
If your visitor is redirected towards a page on which the session_start() was omitted, the information relative to his current session won't be made available on this page (nor will it be possible to change them or add any extra input). However, the session still exists and can be resumed on another page by calling session_start() again. If however the visitor closes his internet session (i.e. closes his session in the browser), his PHP session will be lost.
Accessing PHP session data
When a session is open, the information from this session must be stored within the superglobal variable $_SESSION (which is an array). Therefore, if $_SESSION['firstname']='john' is set from a page where the PHP session is active, it will still be possible to access/modify the content of this variable on any other page of the website, provided that the session is active on that page.
Destroying a PHP session
The PHP command session_destroy() allows you to terminate the current PHP session (provided this session is active on the page from where you are trying to destroy it); when you do so, the $_SESSION variable will be unset.
Session ID: transmission via URL or via the cookies
When a session is started and active, the transmission of the UID (User ID) is done either via the URL (very much like the GET method for HTML forms) or via the cookies (more like the POST method for HTML forms). By default, the cookies method will be adopted, but if your visitor's cookies are disabled, the session ID will automatically be passed via the URL.
Security issues with PHP sessions
PHP sessions can easily be intercepted; for instance, if the UID is transmitted via URL, the UID can be simply extracted from the URL (this is important because if your user is sent to another website through a link containing his UID, that website will be able to intercept the UID and thus access the user's PHP session information). Similarly, if someone manages to intercept your visitor's session cookie, that person will be able to usurp his identity and access his PHP session.
PHP SESSIONS 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),
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).
Reading 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)
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
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: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, thus 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.
We have seen that PHP sessions allow you to pass information relative to a visitor from one page to another, thus making it possible to build dynamic websites.
The purpose of PHP sessions is not to permanently store a given visitor's information (this will be done using web databases) but rather to maintain this information available on your server until the internet session of your visitor expires.
While PHP sessions happen to be very useful, they present security issues and you shall pay attention to the sensitivity of the data that will be kept in cookies or that will appear in URLs; if necessary, you should resort to encryption (PHP encryption will be introduced in the next PHP tutorial).
No comments:
Post a Comment