What are some best practices for handling user input validation in PHP when creating a form for a specific purpose, such as a "Sparschwein"?

When creating a form for a specific purpose like a "Sparschwein," it is essential to validate user input to ensure data integrity and prevent security vulnerabilities. Best practices for handling user input validation in PHP include using server-side validation, sanitizing input data, and implementing client-side validation for a better user experience.

<?php
// Server-side validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $amount = $_POST["amount"];
    
    // Sanitize input data
    $amount = filter_var($amount, FILTER_SANITIZE_NUMBER_INT);
    
    if (empty($amount)) {
        $error = "Please enter a valid amount.";
    } else {
        // Process the form data
        // ...
    }
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <label for="amount">Amount:</label>
    <input type="text" name="amount" id="amount">
    <span style="color: red;"><?php echo isset($error) ? $error : ""; ?></span>
    
    <input type="submit" value="Submit">
</form>