Sessions are part of the PHP that will allow you to transfer data between different parts of the Script and pages. It will allow you to identify each client to the server(and your script) and hold there specific information like there name, address, what they looked at, what they have bought,etc. You can setup a session in two different ways you can use cookies or you can just setup a session.

In this part of our Learning PHP course we will see how to make a session and use it, Lets start:

you can start a session using session_start(), It has to be the first part of the script above everything else:




The above script will tell PHP to create an array that will be shared will all part of your script as long as the “session” is active meaning it hasn’t timed out or logged out or destroyed:


session_start();//starting the session

if(!isset($_SESSION[‘showed’])){// checking to see if the variable showed is set in the session

$_SESSION[‘showed’]=0;// if it is not set set it to 0


$_SESSION[‘showed’]++;// if it is set add one to it

echo $_SESSION[‘showed’];// display the showed variable from session



some HTML code that will give you the option to come back to this page like a login form

After adding HTML code for a form you will have a login page that can count how many time did the user try to login, at this point you can log this information or set a limit so after so many times then using die() function ending the script or using header() function or javascript redirect to another page.

After you are dome with a session you need to end the session you can do this using session_destroy():


session_start();// this will start the session

// some PHP code here to setup and use the session variabels

session_destroy();// this will end the session so you can put it after an if, like: if (count>5){session_destroy();} or something like that


You can use unset() function to clear the session variables like this:



$_SESSION[‘var’]=”some text here”;

if(isset($_SESSION[‘var’])){echo $_SESSION[‘var’];/*this will show sometext here*/}

unset($_SESSION[‘var’]);// this will clear the var in this session

if(isset($_SESSION[‘var’])){echo $_SESSION[‘var’];/*this will show nothing here as var no longer exist*/}



%d bloggers like this: