If the visitor navigates to an another page the value of $name will be lost, so we would need to ask for the name on each page so in this case is way better to use sessions.
In order to use a session first we need to "start" it:
<?phpNOTE: The session_start(); function must be the at the very beginning of your code, even before the <html> tag.
A session variable look`s and works like an element of an associative array:
$_SESSION['name'] = 'Tom';And because sessions are keeping their value even if you go to an another page:
$_SESSION['name'] = 'Tom';
echo $_SESSION['name'] ;
TomLet`s say that we have a page that is displayed only to members. If somebody is logged in than it`s username is stored in a session. In order to show the content of the page to the visitor we need to check if the username session exists or not. This can be easily done using this function:
isset($_SESSION['username']); //Returns True if exists and False if notSo if we use the isset function our code will look like this:
<?phpWhen the user leaves your website or closes the browser the sessions are automatically deleted, but if you want to delete a session yourself use the following code:
echo 'Welcome ' . $_SESSION['username'];
echo 'You are not logged in!';
unset($_SESSION['username']);This is useful when you want to delete only a single session.
If you want to delete all the sessions use the following code:
session_destroy();NOTE: After this function you can`t use more sessions on the page.
Example of using the session_destroy(); function:
session_start();By destroying the sessions the user is logged out.
Here is the original tutorial: php sessions
This is what you need to know about sessions... If you have any questions please ask me!
Edited by Csabi, 06 December 2010 - 11:46 AM.