What best practices should be followed when accessing form data in PHP using $_POST[]?

When accessing form data in PHP using $_POST[], it is important to validate and sanitize the data to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. This can be done by using functions like htmlspecialchars() to sanitize user input and prepared statements to prevent SQL injection. Additionally, always check if the form data exists before accessing it to avoid errors.

// Validate and sanitize form data
if(isset($_POST['username'])) {
    $username = htmlspecialchars($_POST['username']);
}

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);

// Check if form data exists before accessing it
if(isset($_POST['password'])) {
    $password = $_POST['password'];
}