Session – PHP Advanced

It is a way to store data for users against a session ID. Web Server has no idea who you are, has no idea whether you are logged in or you have the permissions to check this page because HTTP address doesn’t maintain state.
And by storing user’s information to be used across multiple pages Session Variables solves the problem. For Example User’s Name. Session variables ends until user closes the browser.
You can store all your data in database if you want a Permanent Storage.

Start Session

Starts with the session_start( ) function.
Variables are stored with PHP global variable $_SESSION.

Creating a new page 

<?php
 // start session
 session_start();          // this session_start(); function should be first before any other html tags.
 ?>
 <!DOCTYPE html>
 <html>
 <body>

<?php
 // set session variables
 $_SESSION["favfood"] = "sandwich";
 $_SESSION["favcolor"] = "black";
 echo "Session Variables Are Set.";
 ?>

</body>
 </html>

 

Output :

Session Variable Values

Now lets create another page.  We will access the session information we stored on our first page from this new page.

<?php
 session_start();
 ?>
 <!DOCTYPE html>
 <html>
 <body>

<?php
 // echo session variables that were set on previous page
 echo "Favorite Food Is " . $_SESSION["favfood"] . ".<br>";
 echo "Favorite Color Is " . $_SESSION["favcolor"] . ".";
 ?>

</body>
 </html>

Output :

Modify Session Variable

Simply overwrite it to modify session variable.

<?php
 session_start();
 ?>
 <!DOCTYPE html>
 <html>
 <body>

<?php
 // to change a session variable, just overwrite it
 $_SESSION["favcolor"] = "Maroon";
 print_r($_SESSION);
 ?>

</body>
 </html>

Output :

Destroy Session

Use session_unset() and session_destroy() to destroy it.

<?php
 session_start();
 ?>
 <!DOCTYPE html>
 <html>
 <body>

<?php
 // remove all session variables
 session_unset();

// destroy the session
 session_destroy();

echo "All session variables are removed & Session is destroyed."
 ?>
</body>
 </html>

Output :

 

 

 

 

 

 

2
Leave a Reply

avatar
1 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Ritesh ChhaudhariAgbolahan Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Agbolahan
Guest
Agbolahan

i really don’t understand this sessions any help?

Ritesh Chhaudhari
Guest
Ritesh Chhaudhari

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP knows to create a new session, and generate a new session ID.