PHP Session is a server-side technology used to store and manage user data during the user's session on a web application. The data can be stored temporarily or persistently and accessed across multiple pages of a web application.
Example 1: Storing User Login Data using PHP Session
session_start();
// check if user is trying to login if(isset($_POST['login'])) { // check user credentials and set session variables $_SESSION['username'] = 'john'; $_SESSION['role'] = 'admin'; header('Location: dashboard.php'); // redirect to dashboard exit(); } ?>
In this example, we’re checking if the user is trying to login with their credentials. Upon successful login, we set session variables username and role and redirect them to the dashboard page.
Example 2: Retrieving User Data and User Data Persistence using PHP Session
session_start();
// check if user is logged in if(isset($_SESSION['username'])) { // retrieve user data $username = $_SESSION['username']; $role = $_SESSION['role'];
// persist user data across multiple pages $_SESSION['lastpage'] = 'dashboard.php'; } ?>
In this example, we’re checking if the user is logged in and retrieving the user data from session variables. Furthermore, we’re persisting the user data across multiple pages by setting the last visited page to the session variable lastpage.
PHP Session is a built-in package and does not require any external libraries.
PHP Session - 30 examples found. These are the top rated real world PHP examples of Session from package huge extracted from open source projects. You can rate examples to help us improve the quality of examples.