How can PHP be utilized to create temporary sessions with specific user rights and expiration dates?
To create temporary sessions with specific user rights and expiration dates in PHP, you can utilize session variables to store user information and set expiration times using timestamps. By setting session variables based on user rights, you can control access to certain functionalities within your application. Additionally, by checking the expiration date against the current time, you can automatically log users out after a certain period of inactivity.
<?php
session_start();
// Set user rights and expiration date
$_SESSION['user_rights'] = 'admin';
$_SESSION['expiration_date'] = time() + 3600; // Expires in 1 hour
// Check if session has expired
if (isset($_SESSION['expiration_date']) && $_SESSION['expiration_date'] < time()) {
// Session has expired, log user out
session_unset();
session_destroy();
header('Location: login.php');
exit;
}
// Access control based on user rights
if ($_SESSION['user_rights'] !== 'admin') {
// Redirect user to unauthorized page
header('Location: unauthorized.php');
exit;
}
// Continue with authorized functionality
echo 'Welcome, admin!';
?>