PHP session tutorial - Starting a session


Home - Tutorials - Sessions

In this tutorial I will show you how to work with sessions in PHP. You will learn how to transfer information between pages.

Tutorial info:


Name:PHP session tutorial
Total steps:5
Category:Sessions
Level:Beginner

Bookmark PHP session tutorial



Bookmark and Share

Step 3 - Starting a session


PHP session tutorial


After the introduction it's time to implement your first session based web site.

First of all you need to start the session with the session_start() function. Note that this function should be  called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data. So for example let's store user name in the session. You can do it as follows:

Code: session.php
  1. $_SESSION['username'] = 'John';
  2.  
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty. So a code which displays the username looks like this:
Code: session2.php
  1. echo "User : ".$_SESSION['username'];
  2.  
That's it. If it doesn't work then check your session settings as mentioned in step 2.





Previous Step of PHP session tutorialNext Step of PHP session tutorial


Tags: php sessions, php, session, session handling



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0261