PHP tutorial - How to use session

best php web server

How To Use Session

Session is a period of time given to a visitor when he or she request a page from your web server. By using session, you will be able to collect information entered by user on your web site such as username or password. Thus, when a visitor enter a username on your login page, this information can be used later on for your entire web site.

The function to start a session in PHP is session_start( ). It has to be placed right on top of the page before any皜PHP or HTML code.

<?php

session_start();

?>

<HTML>
<HEAD>
<TITLE> ........... </TITLE>
</HEAD>

<BODY>
</BODY>
</HTML>

When you tell PHP to start a session, it will randomly generate an ID to be stored into your visitor's web browser as a cookie. So, when he or she browse to another page within your web site, their web browser will send those ID to your web server to identify them.

You can view your own session ID by typing $PHPSESSID.

<?php

session_start();

?>

<HTML>
<HEAD>
<TITLE> ........... </TITLE>
</HEAD>

<BODY>

<?php

echo "Your session is $PHPSESSID";

?>
</BODY>
</HTML>

And the result should looks something like this

your session is 337cfbd0389ed5af188af02bda4e009e

Many web developer including myself like to register a session instead of using hidden fields, cookies or even worst passing sensitive information via URLs to store user preferences and login system. It is more efficient and secure doing it that way.

In PHP, you can register a session by using session_register( ). Let say that you are going to build a login system and use their username for your entire web site setting preferences.

<?php

if($login) {
session_register("userName");
$userName = "David";
}

?>

The above code is just an example of how to register a session in a login system. It is not a complete login system script.

So, after a user had successfully enter their username and password, first of all, you had to register the userName using session_register( ) and then assign the value to it. When this code is executed, PHP will store this session ID to user's computer. It will be accessible as long as the session is still active.

  

Optimize Website - Webmasters optimize their site and gain higher search engine ranking

Free Photo Hosting - Free File Hosting, Free ZIP file Hosting, Free Image Hosting, Free MP3 Hosting.

Funny Videos, Stupid Videos

Stupid Videos - Custom Pimped Motorcycle Pictures, Videos, and Articles

Forectory - Webmaster Directory

St Louis Computer Networking

Website Templates - 1000s of Templates $5 - Many Templates to help you build your site!

 


Each and every tutorial published in PHPhelps.com is originally written by PHPHELPS OWNERS. None of the content is allowed to be replicated without prior notice to writter.
Copyright © 2006 PHPhelps.com