Warning: Trying to access array offset on value of type bool in /home/mukesh88/public_html/www.phpkida.com/wp-content/themes/blog-2020/templates/php.php on line 40

What is a PHP Session?

You already know we can store data using cookies but it has some security issues. Since cookies are stored on user’s computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your application that might break your application easily.

  • A session is a way to store information (in variables) to be used across multiple pages, until user close the website.
  • PHP session is a technique this is most of used in login system and shopping websites where we need to store and pass cart information e.g. username, product code, product name, product price, product quantity etc from one page to another.
  • PHP session creates unique user id for each browser and system to recognize the user and avoid conflict between multiple browsers.

Start a PHP Session

Before you can store any information in session variables, must be first start up the session.
simply a session is started with the session_start() function and session variables are set with the PHP global variable: $_SESSION.
Now, let’s create a simple example of start session and store some value of session in a variable.

<?php
// Start the session
session_start();

// Set session variables
$_SESSION["username"] = "Testing";
$_SESSION["email"] = "youremail@example.com";
echo "Session variables are set.";
?>

How to check PHP Session is set or not

<?php
// Start the session
session_start();

// Set session variables
$_SESSION["username"] = "Testing";
$_SESSION["email"] = "youremail@example.com";
if(isset($_SESSION["username"]))
{
    echo "Session variables (username) is set.";
}
else{
    echo "Session variables (username) is not set.";
}
?>

How get the value of PHP Session Variable

<?php
// Start the session
session_start();

// Set session variables
$_SESSION["username"] = "Testing";
$_SESSION["email"] = "youremail@example.com";
if(isset($_SESSION["username"]))
{
    echo "Session variables (username) is set.";
}
else{
    echo "Session variables (username) is not set.";
}
echo "<br>".$_SESSION["username"]; //get or print the value of php session
?>

How to modify a PHP Session Variable

Here we are simply modify the existing session variable $_SESSION[“username”].

<?php
// Start the session
session_start();

// Set session variables
$_SESSION["username"] = "Testing"; // create the session variable.
$_SESSION["username"] = "Testing Name"; // modify the session variable.

echo "<br>".$_SESSION["username"]; //get or print the value of php session
?>

How to destroy a PHP Session

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

// destroy the session 
session_destroy(); 
?>

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.