Session Management in PHP-part 1

A session is a way to identify and manage the state-the session variables — for a particular user. When a user sends an HTTP request, the middle tier must process the current request in the context of the user’s session. When a session is started, the client is given a session identifier — often a cookie-that is included with subsequent requests to the server. The server uses the session identifier to locate the corresponding session before processing the request.

Rather than storing all the variables needed to maintain state and include them with each request, the browser stores a single session identifier that finds and initializes the variables stored on the server.

Storing session variables in the middle tier is that data needs to be stored for each session. The user logs out of an application, and the logout script ends the session. Sessions consume resources on the server, and dormant sessions may present a security risk. So, the server needs to clean up old sessions that have not been used for a period of time. How long the timeout should be depends on the needs of the application.

While working with the session we must-have to take care of following three things:

  • Information or state must be stored. For example, a students note or instructors feedback, a students name, or id number must be maintained across multiple HTTP requests.
  • Each HTTP request must carry an identifier that allows the server to process the request in the context of the stored state. For example, when any quiz test is submitted, it must be processed with the correct score to display quiz result details.
  • Sessions need to have a timeout . Otherwise, if a user leaves the web site, there is no way the server can tell when the session should end.

When a user first enters the session-based application by making a request to a page that starts a session, PHP generates a session ID and creates a file that stores the session-related variables. PHP sets a cookie to hold the session ID in the response the script generates. The browser then records the cookie and includes it in subsequent requests.

PHP provides a session_start( ) function that creates a new session and subsequently identifies and establishes an existing one. Either way, a call to the session_start( ) function initializes a session. Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.

session_start(); // start up your PHP session!

This code will register the user’s session with the server, allow you to start saving user information and assign a UID (unique identification number) for that user’s session.code, before any HTML or text is sent.

Storing a session variable:

When you want to store user data in a session use the $_SESSION associative array. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.



$_SESSION[‘views’] = 1; // store session data

echo “Pageviews = “. $_SESSION[‘views’]; //retrieve data


Output is:

Pageviews = 1

n this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.

Cleaning session:

After any user completed his/her work in your site like a student complete review and give feedback and left the site, then you want to remove everything from their session variable(like cleanup userid and name for security purpose) you can use following code:






Destroy session:

You can also completely destroy the session entirely by calling the session_destroy function.

A session must be initialized before the session_destroy( ) call can be made. You should also test to see if $PHPSESSID is a set variable before killing the session. This prevents the code from creating a session, then immediately destroying it if the script is called without identifying a session. However, if the user has previously held a session cookie, PHP initializes the $PHPSESSID variable, and the code redundantly creates and destroys a session. You can use following code:

  // Only attempt to end the session if there
  // is a $PHPSESSID set by the request.
  if(isset($PHPSESSID)) {
    $message = "<p>End of session ($PHPSESSID).";
    session_start(  );
    session_destroy(  );
  } else {
    $message = "<p>There was no session to destroy!";
   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "" >

One Laptop Per Child Unveils Plans for Next-Gen Device

One Laptop per Child (OLPC) launched its “$100 laptop,” called the XO, in November 2007 — but at an average price of $188 each. OLPC is committed to achieving an XO-2 target price of $75 when the device launches in 2010. OLPC’s XO-2 laptop is expected to be about the same size as a textbook, with enough memory to store up to 500 e-books.


“Based on feedback from governments, educators and, most important, from the children themselves, we are aggressively working to lower the cost, power and size of the XO laptop so that it is more affordable and usable by the world’s poorest children,” said OLPC founder Nicholas Negroponte.

For details visite: One Laptop Per Child Unveils Plans for Next-Gen Device

Bill Gates Retired from Microsoft

As he said earlier Bill Gates Retired last day at 27th June, 2008 from Microsoft as active one(full time) after 33 years of strong growth and controversy. He still is the chairman of Microsoft. People waits to see The Microsofts future without Bill gates. Because he is the cofounder of the organization and carry this organization one of the worlds top most IT firms with his intellectuality and creativity. Now he wanna spend more time with the Bill & Melinda Gates Foundation, a philanthropic organization that has given more than $16.5 billion in grants worldwide.

He is known as the person who pushed the computer industry to unprecedented success with his goal of a PC in every home. But in 33 years of building Microsoft, Gates has also been characterized by some as a merciless competitor and a monopolist, and even accused of appropriating other people’s ideas.

Bill Gates works:

Starting in 1980, Gates turned an obscure operating system called QDOS into MS-DOS. IBM paid for the development but didn’t retain the rights to MS-DOS. ates supplied MS-DOS and later Windows to thousands of entrepreneurs who assembled PCs with off-the-shelf parts and sold them for much less than IBM.

Along the way, Gates added other software, sometimes buying out competitors or adding their features as Microsoft Office and other software programs grew to dominate the industry. Some claimed the Windows code was manipulated to cripple competitors, and that became an issue in the company’s antitrust battles along with Microsoft taking over the Internet browser market by making Internet Explorer free.

The European Union has also objected to Microsoft’s tactics, leading to some changes in the company’s behavior toward competitors.

Last day he got a tearful farewell from Microsoft and charge handover to Steve Ballmer.


Upload all types of Images with PHP

For very beginners to upload all types of images within with given maximum file size use the following code:

add code to ur interface like profile.php

<form action=”upload.php” method=”post” enctype=”multipart/form-data”>
<label for=”file”>Select an image file:</label> <input type=”file” name=”userfile” id=”file”> <br />
<button>Upload File</button>


Add code to upload.php:

// Configuration – Your Options
$allowed_filetypes = array(‘.jpg’,’.gif’,’.bmp’,’.png’); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = ‘./pics/’; // The place the files will be uploaded to (currently a ‘files’ directory).

$filename = $_FILES[‘userfile’][‘name’]; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,’.’), strlen($filename)-1); // Get the extension from the filename.

// Check if the filetype is allowed, if not DIE and inform the user.
die(‘The file you attempted to upload is not allowed.’);

// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES[‘userfile’][‘tmp_name’]) > $max_filesize)
die(‘The file you attempted to upload is too large.’);

// Check if we can upload to the specified path, if not DIE and inform the user.
die(‘You cannot upload to the specified directory, please CHMOD it to 777.’);

// We’ll start handling the upload in the next step
// Upload the file to your specified path.
if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’],$upload_path . $filename))
echo ‘Your file upload was successful, view the file <a href=”‘ . $upload_path . $filename . ‘” title=”Your File”>here</a>’; // It worked.
echo ‘There was an error during the file upload. Please try again.’; // It failed :(.


Now browse the page to upload image and see the result.

Upload ppt, doc or any kind of file in PHP

Do u have to upload files using PHP ? Files like .ppt, .doc, any kind of image files etc you can upload using following code. Make sure the folder where you want to upload files have write permission.

In your interface(like named resource.php) add the following code:

<form action=”upload.php” method=”post” enctype=”multipart/form-data”>
<label for=”file”>Select a file:</label> <input type=”file” name=”userfile” id=”file”> <br />
<button>Upload File</button>

Now create another page named upload.php to write upload functions:


//set target path where u wanna upload files

$target_path = “./pics/”;

$target_path = $target_path . basename( $_FILES[‘userfile’][‘name’]);
//for upload file this function we use
if(move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $target_path)) {
echo “The file “. basename( $_FILES[‘userfile’][‘name’]).
” has been uploaded”;
} else{
echo “There was an error uploading the file, please try again!”;


Look it is very simple in PHP to upload files for you. Be happy and continue working.

Display data from mysql into combobox in PHP

For very beginners It is not easier to display data from required mysql table into combobox in PHP. Again after call any javascript function from that control’s onClick which will submit the page, always display only first or last data into combobox as well as it takes same value as input which bother developers. So in php there is easier way to handle such a problem. I have a table named casa_session from where I have to display session_title into select field. The codes are follows:

<? include(“connection.php”) ?>

<TR HEIGHT=”25″>
<TD colspan=”2″>Semester</TD>
<select name=”salSemesterID” onClick=”submitCboSemester();”>
$query_disp=”SELECT * FROM casa_semester order by semester_id asc”;
$result_disp = mysql_query($query_disp, $conn);
while($query_data = mysql_fetch_array($result_disp))
<option value=”<? echo $query_data[‘semester_id’]; ?>”<?php if ($query_data[‘semester_id’]==$_POST[‘salSemesterID’]) {?>selected<? } ?>><? echo $query_data[‘name’]; ?></option>
<? } ?>

Now it works fine.

Firefox 3 Add-Ons: with Business Friendly Tools


17th June, 2008 was the Firefox3 download day. If you need a faster and more secure open source web browser than earlier? Use Mozilla Firefox 3 which is highly customizable for individual users by utilizing the massive library of Add-ons – additional features that users can choose to install on top of the browser. The overall usefulness of an add-on can be measured by its ability to help the user without opening more tabs, and these add-ons seem to do that well.

There are five Add-Ons business-friendly tools:

1. LinkedIn Companion

2. Google Preview

3. TwitterFox

4. Colorful Tabs

5. Delicious Bookmarks

We give a summery on their functionality below:

1. LinkedIn Companion For Firefox 3.1.1:

LinkedIn is the online social network for business contacts. It is a prominent way to connect with colleagues and friends in the professional world. You can utilize your connections on LinkedIn in other applications(such as Gmail and Yahoo mail) without having to keep LinkedIn open as a tab on your web browser.

If you open an email in Gmail from your friend Anita, a info logo will appear next to that persons name. By scrolling mouse over it, you will have a link through which you can visit that persons LinkedIn profile. It will also show all connections you share in your area, besed on the information LinkedIn members provide.

2. Google Preview:

When you forget to bookmark a page, you probably turn to Google and search for it. But when you get to the results page, sometimes it’s hard to remember which one you clicked on. (Sometimes the browser will change the color of the link, but not always). With Google Preview, you can see a small version of the web-page that the link will lead you to, which should help jar your memory and avoid the need to click on several results to see which one you picked last time.

3. TwitterFox:

Twitter, a social networking service that keep track of colleagues, friends, and even customers. With TwitterFox, you can let this information feed to your browser without it being too disruptive. After installation, a small “T” resides in the corner. When a number appears next to it (say “1”), you know some of your friends have posted a “tweet” (a message on Twitter). The number increases as more unread messages compile. You can click on the box when you want to see what they’ve written. There is also an option to let their messages pop up for a few seconds in the corner above the T.

4. ColorfulTabs:

ColorfulTabs are a great carryover from previous versions of Firefox that works on Firefox 3. ColorfulTabs allows you to differentiate what tabs you’re working under automatically (it will assign a color) or manually (you can set one). One could set Gmail tab to blue and to red, for instance. You can change the colors right away by right clicking on the tab.

The business value of this add-on is quite simple: if you have a Web-browser open all day for your job, having colors (rather than a static gray look) makes it easier on the eyes to differentiate the applications and websites you have open.

5. Delicious Bookmarks:

Delicious is a social bookmarking site that allows you to save your bookmarks in once centralized location that you can access with a login and password regardless of what computer or browser you are on. This can be especially helpful if you are looking to share relevant pieces of content (news, etc.) with colleagues at work but aren’t on the company intranet. Customers who also use the service could share content with you.

Like TwitterFox, Delicious Bookmarks for Firefox 3 now utilizes the right corner of the browser. There, you can see the symbol. If you click on it, you will be led to your home page on the social bookmarking site where you store your favorite articles and websites (and tag them). If you utilize the social aspects of (meaning, primarily, that you share bookmarks with friends on the service), you can also be notified that a friend has shared a link with you. Like the older versions of this add-on, you have a button at the top of your browser installed that says “Tag,” which will allow you to save a page for bookmarking and tag it with a relevant label. Also, like on previous versions, if you right click on an article it will say “bookmark this in”