How to PHP Scripting- PHP Sessions
A PHP session creates a file in a temporary directory on the server where registered session variables and their values are stored. You 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.
Session variables are used to store individual client’s information on the web server for later use, as a web server does not know which client’s request to be respond because HTTP address does not maintain state.
Start a PHP Session
Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
<?php session_start(); // Do Something ?>
Storing and Accessing Session Data
To store variables relevant to the session, assign what you want to a member of the $_SESSION array.
<?php session_start(); // Store Session Data $_SESSION['login_user']= $username; // Initializing Session with value. ?>
To access those variables, simply reference it as you would any PHP array.
<?php session_start(); // Store Session Data $_SESSION['login_user']= $username; echo $_SESSION['login_user']; ?>
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables.
<?php session_destroy(); ?>
Cookies vs Session
|Cookies are small files that are stored in the visitor's browser.||Sessions are small files that are stored on the website's server.|
|Cookies can have a long lifespan, lasting months or even years.||Sessions have a limited lifespan; they expire when the browser is closed.|
|Cookies are limited in size depending on each browser's default settings.||Sessions are only limited in size if you limit their size on the server.|
|Cookies can be disabled if the visitor's browser does not allow them (uncommon).||Sessions cannot be disabled by the visitor because they are not stored in the browser.|