PHP - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Sessions

PHP Sessions

shape Introduction

Form Validation is a big level challenge when reusing the form page to display validation errors. POST data has to be carried to the next page.This can be accomplished using PHP Sessions.

shape Description

Sessions are same as cookies, but sessions are very secure and the user data won't be saved in the users browser. It will save on the server side and generates a encrypted key that will save in the browser and the data can be used in multiple pages in website. Session saves the users data in secured manner compare with cookies.

Starting PHP Sessions

shape Description

The session will start with session_start() function and $_SESSION is superglobals variable.Similar to the cookies start session before <html> tag. Syntax:
bool session_start([array $options=[]])

shape Example

php-sessions.php [php] <!DOCTYPE html> <?php session_start(); // Start the session ?> <html> <body> <?php // Set session variables $_SESSION["name"] = "John"; $_SESSION["mobile"] = "0123456789"; echo "Session variables are set."; ?> </body> </html> [/php]

Accessing Session

shape Example

Here in from the xyz.php file, the Session being accessed which is created previously. [php] <!DOCTYPE html> <?php session_start(); ?> <html> <body> <?php //Session Variables data that were set on previous page echo "Name : " . $_SESSION["name"] . ". "; echo "Mobile : " . $_SESSION["mobile"] . "."; ?> </body> </html> [/php]

Destroy or Delete a PHP Session

shape Example

The global session variable can be destroyed using session_unset() and session_destroy(). [php] <!DOCTYPE html> <?php session_start(); ?> <html> <body> <?php session_unset(); // removes all session variables session_destroy(); // destroy the session ?> </body> </html>[/php]

Summary

shape Key Points

  • session_start() function starts the session.
  • session_unset() and session_destroy() destroys the session.