What are the differences between using cookies and sessions for managing user login sessions in PHP?
Using cookies for managing user login sessions in PHP stores session information on the client side, while using sessions stores session information on the server side. Cookies can be manipulated by the client, potentially posing a security risk, while sessions are more secure as the session data is stored on the server. Sessions also provide more flexibility in terms of session management and data storage.
// Using sessions for managing user login sessions in PHP
session_start();
// Set session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
// Check if user is logged in
if(isset($_SESSION['user_id'])){
echo "User is logged in";
} else {
echo "User is not logged in";
}
// Destroy session on logout
session_destroy();