2. To start a session in PHP, you need to call the
session_start() function at the beginning of your script. This
function initializes the session and makes session-related
data accessible via the $_SESSION superglobal.
2
4. To store data in the $_SESSION array to make it
accessible across multiple requests. This data persists
until the session is destroyed or the user logs out.
$_SESSION['username'] = 'john_doe';
$_SESSION['cart'] = ['item1', 'item2', 'item3'];
4
5. To retrieve data from a session, you can simply access
the $_SESSION array.
$username = $_SESSION['username'];
$cartItems = $_SESSION['cart'];
5
6. To modify session data just like any other PHP array.
$_SESSION['cart'][] = 'item4'; // Add an item to the cart
$_SESSION['username'] = 'jane_doe'; // Update the
username
6
7. To remove a specific item from the session, you can use
the unset() function.
unset($_SESSION['cart'][1]); // Remove the second item
from the cart
7
8. To end a session, call the session_destroy() function. This
clears all session data and cookies associated with the
session. However, this doesn't unset the $_SESSION
superglobal, so any session data set during the script
execution will still be accessible until the script finishes
running.
session_destroy();
8
9. Sessions have a timeout period defined in PHP
configuration. By default, this is set to 24 minutes. If a
user remains inactive for this duration, their session data
will be automatically destroyed.
9
10. Sessions should be used carefully to avoid security risks
like session fixation, session hijacking, and session data
manipulation. To enhance security, use techniques like
session ID regeneration (session_regenerate_id()) and
use secure cookies.
10
11. // During login
if ($validCredentials) {
$_SESSION['user_id'] = $userId;
}
// On protected pages
session_start();
if (!isset($_SESSION['user_id'])) {
// Redirect to login page
}
11