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.
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."; ?>
<?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."; } ?>
<?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 ?>
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 ?>
<?php // start session session_start(); // remove all session variables session_unset(); // destroy the session session_destroy(); ?>