Learning PHP Sessions

$_SESSION's are useful in a lot of ways such as user systems.

Many sites use them such as paypal.com,bidvertiser and some other sites. For security reasons people use sessions more then cookies because a user can steal someones cookie easier then a session. And verify that there that user.

So what is a session?
Well a session is basically A Temporary Storing box. I say Temporary because it's stores information until you shut your page down or browser down depending on what browser your running.

How is it useful?
Its useful because instead of storing information on your computer it deletes it's self so it can't be reused again. This doesn't delete nothing on your site it just deletes the stored information so that no one can take your identity in any way.

How do you use it?

From reading php.net it clearly states that you must start the page thats using sessions and PHP with session_start();. This must go at the heading of your page before html in most cases.


CODE
<?php session_start(); ?>

<!-- HTML Here -->



The reason you must have session_start(); at the top of your page is because its the start up phase to make functions work. It's like saying you have to start up the engine of a car to make it go.

We'll what if you have a session that you want for a certain period of time?
The best way to do this is use unset();
What unset will do is remove the contents of a variable. Basically deleting everything attached to that variable created.

How would we do that with $_SESSION['variable']; ?
First you would have to create a session.


CODE
<?php
session_start
();

if(!
$_SESSION['test']){//if this session doesn't exist we simply create it.
$_SESSION['test'] = "Guest";
}

echo 
$_SESSION['test']."";//echo test out. Would output "Guest"
unset($_SESSION['test']);
echo(
$_SESSION['test']);//Echo test out again. It will display nothing.
?>



See above how we set a session if it wasn't created using a simple if statement. So first we checked to see if there was a session. Then if there wasn't a session we simply set one. Next we echoed the outcome with a line break to show the session again on a new line,but we used unset() to remove the session because we didn't want to use it any more and echoed the session again but we removed it so it displayed nothing.

Live Example of above session_test1.php

This tutorial went over how to make sessions,how to remove certain sessions and what you need to use to start a session. If This tutorial helped Please Join Our Forums now.

Sunday May 27, 2007 | http://www.totaldream.org/article/30-learning_php_sessions.html