0

I have the following error handlers in my PHP file:

if (empty($title) || empty($description) || empty($price)) {
    header("Location: ../listing1.php?error=emptyfields");
    exit();
} elseif (!is_numeric($price)) {
    header("Location: ../listing1.php?error=onlynumbers");
    exit();
}

But when I type in accordance with the is_numeric error handler it returns false telling it's error=emptyfields. I have tried switching positions but it still returns false and now I'm lost, though when I type in anything above 0 it returns true.

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
  • Please show the values of your variables, otherwise we can't help. – Jeto Dec 22 '18 at 21:16
  • Why don't you give us a sample input that your code receives. – Difster Dec 22 '18 at 21:16
  • `var_dump($title, $description, $price);` – Pinke Helga Dec 22 '18 at 21:18
  • They are from an HTML form, values are the following: `$title = $_POST['title']; $description = $_POST['description']; $price = $_POST['price'];`, the column in the DB is set to null as well. –  Dec 22 '18 at 21:19
  • If `$price` is a number, then when `$price` is `0` or `"0"`, `empty($price)` will return `true`. If you want to handle when `$price` is `0`, you're going to need to be careful about your `empty($price)` check. Note that `is_numeric(0)` and `is_numeric("0")` will return `true`, and `empty(0)` and `empty("0")` will return true. The concept of "empty" doesn't necessary mean "no value". – B. Fleming Dec 22 '18 at 21:20
  • A sample would be: `test - test - 0`, that should be allowed which is the problem I'm trying to figure out. –  Dec 22 '18 at 21:21
  • Please `var_dump` all these variables and edit your question with the output, as @Quasimodo'sclone suggested. – Jeto Dec 22 '18 at 21:22
  • empty will returns `true` if the variable is `0` ( or string `"0"` ). Zero is empty. – Federkun Dec 22 '18 at 21:24

1 Answers1

0

PHP's empty() function will consider the values 0 and "0" to be empty. Thus, even though the value is numeric and is properly set, it will still result in incorrect behavior.

You're going to need to be more careful about your first if condition. Instead of just empty($price), maybe consider doing (empty($price) && $price !== 0 && $price !== "0"). This is a much lengthier, more verbose validation, but it should eliminate the error.

B. Fleming
  • 7,170
  • 1
  • 18
  • 36
  • `empty` is true when a variable is unset, thus your code will generate notices. `!isset($price) || $price === ""` is all what we need here. – Pinke Helga Dec 22 '18 at 22:02