What are the best practices for using $_POST and $_SESSION superglobals in PHP?

When using $_POST and $_SESSION superglobals in PHP, it is important to sanitize and validate user input from $_POST to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, it is recommended to use $_SESSION to store sensitive information that needs to persist across multiple pages for a particular user session.

// Sanitize and validate user input from $_POST
$username = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';

// Store sensitive information in $_SESSION
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;