What are the differences between using cookies and sessions for user authentication in PHP?

When it comes to user authentication in PHP, both cookies and sessions can be used to store user information. Cookies are stored on the user's browser while sessions are stored on the server. Cookies can be set to expire after a certain period of time, while sessions typically expire when the user closes their browser. Sessions are generally considered more secure for storing sensitive user information as they are stored on the server-side.

// Using sessions for user authentication in PHP
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is logged in
    echo "Welcome, ".$_SESSION['username']."!";
} else {
    // User is not logged in, redirect to login page
    header("Location: login.php");
    exit();
}