How can you ensure that users input only numeric values in a PHP form and display an error message if they don't?

To ensure that users input only numeric values in a PHP form, you can use client-side validation with JavaScript to check the input as the user types. If the input is not numeric, you can display an error message to prompt the user to enter a valid numeric value. Additionally, you can also perform server-side validation in PHP to double-check the input before processing it.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = $_POST['numeric_input'];

    if (!is_numeric($input)) {
        $error_message = "Please enter a valid numeric value.";
    } else {
        // Process the input if it is numeric
    }
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="numeric_input">
    <input type="submit" value="Submit">
    <?php if(isset($error_message)) { echo $error_message; } ?>
</form>