In PHP, what are some best practices for handling form submissions and validating user inputs to ensure data integrity and security?

When handling form submissions in PHP, it is important to validate user inputs to ensure data integrity and security. Some best practices include using server-side validation to check for required fields, data types, and lengths, sanitizing user inputs to prevent SQL injection and cross-site scripting attacks, and using prepared statements to interact with the database securely.

// Example of validating user input and preventing SQL injection
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = htmlspecialchars($_POST["username"]);
    $password = htmlspecialchars($_POST["password"]);

    // Validate required fields
    if (empty($username) || empty($password)) {
        echo "Username and password are required.";
    } else {
        // Sanitize user inputs
        $username = filter_var($username, FILTER_SANITIZE_STRING);
        $password = filter_var($password, FILTER_SANITIZE_STRING);

        // Prepare and execute SQL query using prepared statements
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':password', $password);
        $stmt->execute();

        // Process query results
        $user = $stmt->fetch();
        if ($user) {
            echo "Login successful!";
        } else {
            echo "Invalid username or password.";
        }
    }
}