0

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
  • 8,415
  • 9
  • 52
  • 80
Luke
  • 35
  • 1
  • 6
  • So what is your expected output for each situation? –  Jun 27 '16 at 17:25
  • If the amount is empty - I got 'Empty amount' error. If the amount is not between $amountMin and $amountMax - I got 'Incorrect amount' error. – Luke Jun 27 '16 at 17:26

1 Answers1

0

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.

cb0
  • 8,415
  • 9
  • 52
  • 80
  • It's working perfectly! I have just one more question: should I use exit;, exit(), die(), or die() after header() function? Else, you should edit your post using `!filter_var()` but not `filter_var()`. – Luke Jun 27 '16 at 17:44
  • 1
    Glad it works! For your question: die() and exit() are equivalent function. See [here](https://stackoverflow.com/questions/1795025/what-are-the-differences-in-die-and-exit-in-php#21883156.). Personally I prefer `exit(0)` if everything went as it should – cb0 Jun 27 '16 at 17:47
  • Thank you for the answer! But should I use `exit;` after header() function or it's not necessary? – Luke Jun 27 '16 at 17:50
  • The manual says you only need to use `exit` if you want to ensure that no following code is executed, after the header has been redirected. If your script ends after `header` call, you could skip it. But I think it's more clear and readable to write `exit` after header. – cb0 Jun 27 '16 at 17:54