Luke Luke - 5 months ago 9
PHP Question

PHP error using variables

This is my code:

$amountError = '';
$amountMin = 0.50; // Minimum amount
$amountMax = 100; // Maximum amount

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['amount'])) {
$amountError = 'Empty amount';
}
if (!filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT,
array("options" => array(
"min_range"=>$amountMin,
"max_range"=>$amountMax))) === false) {
header('Location: apmoketi.php');
exit; // Should I use it?
} else {
$amountError = 'Incorrect amount';
}
}


The problem is, if the amount is empty, I'm getting 'Incorrect amount', but not 'Empty amount' error. And if the amount is filled in but not between
$amountMin
and
$amountMax
then I got redirected to 'apmoketi.php' page, but don't get the 'Incorrect amount' error.
How do I fix that?

cb0 cb0
Answer

You can leave off the ! and the ===false and restructure your code like this.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (empty($_POST['amount'])) {
        $amountError = 'Empty amount';
    } elseif (filter_var(
            $_POST['amount'], FILTER_VALIDATE_FLOAT,
            array("options" => array(
                "min_range" => $amountMin,
                "max_range" => $amountMax)))
    ) {
        header('Location: apmoketi.php');
        exit; // Should I use it?
    } else {
        $amountError = 'Incorrect amount';
    }
}

You are alway overwriting the $amountError with "Incorrect amount" if no valid float in the range $amountMin to $amountMax was given.