php - Protection against tampered user input and SQL injection fails

759

So I have a form with 2 text inputs. One is price and the other is quantity. Before saving the form there are some checks that act as safeguard against tampered user input and SQL injection.

so one of them is:

    if(strval(floatval($quantity)) === $quantity && strval(floatval($price)) === price) {
      $errors = false;
   }

The problem with this check is that if we have $price = "47.80" for example floatval() gives us 47.8 and then strval() gives us "47.8" which does not equal to "47.80" So the check fails and we get an error.

I would like to know if you can think of a way to go around this without changing the logic too much.

949

Answer

Solution:

You can use the filter extension:

$price = filter_var($price, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

It removes everything that is not a digit or a period.

If the number has to have two decimal points then you have to somehow enforce that. You can either not allow numbers without two decimal points or you can fix the input yourself. Something like this should do:

$price= number_format($price, 2, '.', null);

People are also looking for solutions to the problem: magento - PHP rounding issue

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.