What are best practices for handling variables passed through links or forms in PHP scripts?

When handling variables passed through links or forms in PHP scripts, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to do this is by using PHP functions like htmlspecialchars() to escape special characters and filter_input() to validate input. Example PHP code snippet:

// Sanitize and validate input from a form field
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);

// Escaping output to prevent XSS attacks
echo htmlspecialchars($username);