How can session variables be effectively used in PHP to store and retrieve user information for specific actions like posting an ad?

Session variables can be effectively used in PHP to store and retrieve user information for specific actions like posting an ad by setting the necessary user data in session variables when the user logs in and then accessing this data on the posting ad page. This allows for easy retrieval of user information without the need to constantly pass data through URLs or forms.

// Start the session
session_start();

// Set user information in session variables when the user logs in
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;

// Retrieve user information for posting ad
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// Use the user information for posting ad
echo "User ID: " . $user_id . "<br>";
echo "Username: " . $username;