What are some best practices for handling variables in PHP to avoid security vulnerabilities?

One best practice for handling variables in PHP to avoid security vulnerabilities is to always sanitize and validate user input to prevent SQL injection and cross-site scripting attacks. This can be done using functions like mysqli_real_escape_string() and htmlspecialchars(). Additionally, it's important to avoid using global variables whenever possible to prevent data leakage. Example PHP code snippet:

// Sanitize and validate user input
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);

// Avoid using global variables
function login($username, $password) {
    // Function logic here
}