php7 how to check, that only int values in html form

FSp1333 Source

this code accepts numbers, e.g. 13.5, 15.6 etc... I need that checked if this is a number only int, e.g. 13, 14 ... etc.

if (is_numeric($r_haslo) == false) {
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}
phpif-statement

Answers

answered 4 months ago Joseph_J #1

You can us is_int() to check.

if (is_int($r_haslo) == false) {
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}

answered 4 months ago thatguy #2

if it has to be an integer and integer only this is how I like to do it.

if (is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) {
    //is an integer
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}

With the updated code above, this now makes sure that $r_haslo is not a number first, and if it is a number, that the number is not an int. So if it's not a number or not an int then it will save the warning to the session.

This way if I send 23 and "23" both are true.
If I send 23 and "23" to is_int() function only 23 will be true.

If you never send string input then is_int() is probably the better way to go.

Update

if (strpos($mystring, ".") || is_numeric($r_haslo) == false || ((int)$r_haslo != $r_haslo)) 
{
    //is an integer
    $wszystko_ok = false;
    $_SESSION['e_haslo'] = "<i class=\"fas fa-user-times\"></i> Podaj tylko cyfry!";
}

The updated code above will also make sure that there is not a '.' in the input.

Note
if the value is being passed as a number, PHP will automatically convert 12.0 and 12. to 12. if the value is being passed as a string, the srtpos() method will catch it.

answered 4 months ago Progrock #3

When you say this code accepts, I'll interpret that as you are taking user input by way of a HTTP POST or GET.

The following will only assign and cast to an integer if the posted string contains digits (an unsigned integer within) otherwise it will be assigned null.

<?php
$id = isset($_POST['id']) && ctype_digit($_POST['id'])
    ? (int) $_POST['id']
    : null;

comments powered by Disqus