Sunday, December 9, 2012

PHP Sessions - Advanced PHP For Beginners Lesson 9


PHP SESSIONS
By Stephon Unomon

 

       When your websites start to become more advanced and you find that you have a need for specific user data to be available throughout different pages on your website (think shopping cart!), it’s time for Sessions!

 

Starting a session is a snap.

 

<?php

session start();

?>

The webserver will attach a really really long random “session ID” to indicate a unique session. It looks something like: a8486dd2a3eacc136bd44ca653d8c5a2

 

A session isn’t worth a hill of beans unless we can store data in it. Fortunately, PHP can do this for us with an associative array, based on the $_SESSION variable. (Is some of this starting to come together?)

 

Let’s make a login form based on sessions!

 

<?php

session_start(); //  Starts a PHP session

echo "<form method=POST action=index.php>

  User Name: <input type=text name=\"username\">

  Password: <input type=text name=\"password\">

  <input type=submit>

  </form>";  // This is the HTML form

$_SESSION['username']=$_POST["username"]; // Enters the username into the array

$_SESSION['password']=$_POST["password"]; // Enters the password into the array

?>

 

Your username and password are now stored in an array that will last until the session is “un-set”.

 

Removing a session is done when either: The viewer closes their browser, or PHP runs the command to un-set a session, aka “destroy”.

 

You can think of it like this - your session is an Etch-a-Sketchtm that has information drawn on it. It’s there until you shake it!

 

<?php

session_destroy();

?>

Yes, it’s a tad violent...but gets the job done. This will clear out any data associated with the current session.

 

So, what if I want to remove specific data from a session without deleting the whole thing?

 

This can be done with an IF statement combined with  commands called “ISSET” and “UNSET”.

 

<?php

if(isset($_SESSION['items'])){ 

unset($_SESSION['items']);}

?>

 

So, logically...

 

If this specific key is set in this session, remove the key’s data.

The Best PHP Editor

No comments:

Post a Comment