Working With PHP Sessions

Started by Sudhakar, Jun 02, 2009, 10:22 PM

Previous topic - Next topic

Sudhakar

PHP Session Tutorial - Starting a session

First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data. So for example let's store user name in the session. You can do it as follows:


1. session_start();
2. $_SESSION['username'] = 'Matt';

If you want to display the username you need to start the session again. In
this case PHP checks whether session data are sored with the actual id
or not. If it can find it then initialise the $_SESSION array with that
values else the array will be empty. So a code which displays the
username looks like this:


1.session_start();
2.echo "User : ".$_SESSION['username'];

PHP Session Tutorial - Check sessions

To check whether a session variable exists or not you can use the isset() function.


1. session_start();
2. if (isset($_SESSION['username'])){
3. echo "User : ".$_SESSION['username'];
4. }else {
5. echo "Set the username";
6. $_SESSION['username'] = 'Matt';
7. }

However if you have executed the first example as well then you will never get the message "Set the username" as you have done it in your very first call. If you wait until the session is expired and execute the code again you will get the set message.


PHP Session Tutorial - Clean and Destroy a Session

To remove a variable from a session is quite easy. You just have to call the unset() function to do this. Now you can extend our example code to unset the username as follows:


1. session_start();
2. if (isset($_SESSION['username'])){
3. echo "User : ".$_SESSION['username'];
4. unset($_SESSION['username']);
5. } else {
6. echo "Set the username";
7. $_SESSION['username'] = 'Matt';
8. }


You can use the session_destroy() function if you want to remove all session data, but be careful with it.


1. session_start();
2. if (isset($_SESSION['username'])){
3. echo "User : ".$_SESSION['username'];
4. session_destroy();
5. } else {
6. echo "Set the username";
7. $_SESSION['username'] = 'Matt';
8. }