PHP Session Implementation for User Login Functionality
Category Programming Technology
Compared to Cookies, Sessions are stored on the server side, which is relatively secure and not limited by storage length like Cookies. This article briefly introduces the use of Sessions.
Since Sessions are stored as text files on the server side, there is no fear of clients modifying the Session content. In fact, on the server side, PHP automatically modifies the permissions of the Session files, retaining only the system's read and write permissions, and making them unmodifiable via FTP, thus providing more security.
For Cookies, suppose we need to verify whether a user is logged in; we must save the username and password (possibly an md5 encrypted string) in the Cookie and validate them every time a page is requested. If the username and password are stored in a database, a database query must be executed each time, adding unnecessary burden to the database. This is because we cannot perform a single validation. Why? Because the information in the client-side Cookie can be modified. If you store a variable $admin to indicate whether the user is logged in, with $admin being true for logged in and false for not logged in, and after the first validation, you store $admin as true in the Cookie for future validations, is this correct? No, if someone fakes a $admin variable with a value of true, they would immediately gain administrative privileges, which is highly insecure.
Sessions, on the other hand, are stored on the server side, and remote users cannot modify the content of the Session files. Therefore, we can simply store a $admin variable to check if the user is logged in. After the initial validation, set the $admin value to true, and then check if this value is true in subsequent validations. If not, redirect to the login page, which reduces many database operations and eliminates the insecurity of passing passwords for Cookie validation each time (Session validation only needs to be passed once, unless you are not using the SSL security protocol). Even if the password is md5 encrypted, it can still be intercepted easily.
Of course, using Sessions has many other advantages, such as easy control and customizable storage (in a database). I won't go into detail here.
Does Session need to be set in php.ini? Generally not, as not everyone has the permission to modify php.ini. The default storage path for Sessions is the system's temporary folder, but we can customize it to be in our own folder, which I will introduce later.
Let's start by introducing how to create a Session. It's really simple.
Start a Session and create a $admin variable:
Example
<?php
// Start Session
session_start();
// Declare a variable named admin and assign it a null value.
$_SESSION["admin"] = null;
?>
If you use Sessions, or if the PHP file needs to call Session variables, you must start the Session before calling it using the session_start() function. Other settings are handled automatically by PHP, which creates the Session file.
After executing this program, we can find the Session file in the system's temporary folder. The file name is usually in the form: sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-character random string. Open it with an editor to see its content:
admin|N;
The general structure of this content is:
variable name|type:length:value;
Each variable is separated by a semicolon. Some parts, like length and type, can be omitted.
Let's look at the validation program, assuming the database stores usernames and md5 encrypted passwords:
login.php File Code
<?php
// After form submission...
$posts = $_POST;
// Clear some whitespace characters
foreach ($posts as $key => $value) {
$posts[$key] = trim($value);
}
$password = md5($posts["password"]);
$username = $posts["username"];
$query = "SELECT `username` FROM `user` WHERE `password` = '$password' AND `username` = '$username'";
// Get query result
$userInfo = $DB->getRow($query);
if (!empty($userInfo)) {
// Start Session when validation passes
session_start();
// Register the successful login admin variable and assign it true
$_SESSION["admin"] = true;
} else {
die("Incorrect username or password");
}
?>
We need to start the Session on pages that require user verification to determine if the user is logged in:
Example
<?php
// Prevent security risks from global variables
$admin = false;
// Start session, this step is essential
session_start();
// Check if logged in
if (isset($_SESSION["admin"]) && $_SESSION["admin"] === true) {
echo "You have successfully logged in";
} else {
// Validation failed, set $_SESSION["admin"] to false
$_SESSION["admin"] = false;
die("You are not authorized to access");
}
?>
Isn't it simple? Think of $_SESSION as an array stored on the server side, where each registered variable is a key in the array, and using it is no different from using an array.
What if you want to log out of the system? Destroy the Session.
Example
<?php
session_start();
// This method destroys a previously registered variable
unset($_SESSION['admin']);
// This method destroys the entire Session file
session_destroy();
?>
Can Sessions be set with a lifespan like Cookies? Do you completely abandon Cookies when you have Sessions? I would say that using Cookies in conjunction with Sessions is the most convenient.
How does Session determine the client user? It does so by identifying the Session ID, which is the file name of the Session file. The Session ID is randomly generated, ensuring uniqueness and randomness, which helps ensure Session security. Typically, if the Session lifespan is not set, the Session ID is stored in memory and is automatically canceled when the browser is closed. Upon re-requesting the page, a new Session ID is registered.
If the client does not disable Cookies, Cookies play a role in storing the Session ID and the Session lifespan when the Session is initiated.
Let's manually set the Session lifespan:
Example
<?php
session_start();
// Save for one day
$lifeTime = 24 * 3600;
setcookie(session_name(), session_id(), time() + $lifeTime, "/");
?>
In fact, Session provides a function session_set_cookie_params(); to set the Session lifespan, which must be called before the session_start() function:
Example
<?php
// Save for one day
$lifeTime = 24 * 3600;
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>
If the client uses IE 6.0, there may be issues with setting Cookies using the session_set_cookie_params(); function, so we manually call the setcookie function to create the cookie.
What if the client disables Cookies? There's no way; the lifespan is now the browser process. As soon as the browser is closed, the next page request will require re-registering the Session. How do we pass the Session ID then? By URL or hidden form, PHP automatically sends the Session ID to the URL, which looks like: http://www.test.cn/index.php?PHPSESSID=bba5b2a240a77e5b44cfa01d49cf9669, where the parameter PHPSESSID in the URL is the Session ID. We can use $_GET to retrieve this value to pass the Session ID between pages.
Example
<?php
// Save for one day
$lifeTime = 24 * 3600;
// Get the current Session name, default is PHPSESSID
$sessionName = session_name();
// Get the Session ID
$sessionID = $_GET[$sessionName];
// Use session_id() to set the obtained Session ID
session_id($sessionID);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?>
For virtual hosts, if all users' Sessions are saved in the system's temporary folder, it complicates maintenance and reduces security. We can manually set the Session file's save path, which session_save_path() provides. We can point the Session storage directory to a folder that cannot be accessed via the Web, as long as the folder has read and write permissions.
Example
<?php
// Set a save directory
$savePath = './session_save_dir/';
// Save for one day
$lifeTime = 24 * 3600;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
$_SESSION['admin'] = true;
?>
Like the session_set_cookie_params(); function, the session_save_path() function must be called before the session_start() function.
We can also store arrays and objects in Sessions. Operating on arrays is no different from operating on regular variables, and storing objects results in PHP automatically serializing the object and saving it in the Session. The following example illustrates this:
person.php File Code
<?php
class person {
var $age;
function output() {
echo $this->age;
}
function setAge($age) {
$this->age = $age;
}
}
?>
setage.php File Code
<?php
session_start();
require_once 'person.php';
$person = new person();
$person->setAge(21);
$_SESSION['person'] = $person;
echo '<a href='output.php'>check here to output age</a>';
?>
output.php File Code
<?php
// Set callback function to ensure object reconstruction.
session_start();
if (isset($_SESSION['person'])) {
$person = $_SESSION['person'];
$person->output();
} else {
echo "No person data found.";
}
?>
ini_set('unserialize_callback_func', 'mycallback');
function mycallback($classname) {
include_once $classname . '.php';
}
session_start();
$person = $_SESSION['person'];
// Output 21
$person->output();
?>
When we execute the setage.php file, the setage() method is called, setting the age to 21, and the state is serialized and saved in the Session (PHP automatically handles this conversion). When we switch to output.php, to output this value, we must deserialize the previously saved object. Since deserialization requires instantiating an undefined class, we define a callback function to automatically include the person.php class file. Therefore, the object is reconstructed, and the current age value of 21 is obtained, then the output() method is called to output this value.
Additionally, we can use the session_set_save_handler function to customize the Session handling method.
Original Source: https://www.cnblogs.com/happyforev1/articles/1645916.html ```