php validate number

Hi I want to make sure the value entered is between 0-9. when I use the code below it keeps calling the die function even when the value entered is inbetween 0-9.

How do I run it through the filter and check if it is valid?

thanks!
$int_preChorusQ = array("options"=>
array("min_range"=>0, "max_range"=>9));

if (!filter_var($preChorusQ, FILTER_VALIDATE_INT, $int_preChorusQ)){
die('The quantity you entered is not valid');
}

Open in new window

SolutionabcAsked:
Who is Participating?
 
Ray PaseurConnect With a Mentor Commented:
"it will not allow 2 characters in the user input box"

Sorry - that's not good enough.  A hacker can post anything directly into your script - the HTML of the form and the JavaScript on the server side may be conveniences for your client, but those are completely useless as a security measure.

If you have only a single digit, you are safe against SQL injection.  In fact, if you have a properly escaped string you are safe against SQL injection (See mysql_real_escape_string() for more.  But there are many other kinds of issues in PHP security, and threats are evolving constantly.  That's why it's a good idea to do this search every month or two and give yourself a moment to look over the web pages that turn up.

http://lmgtfy.com?q=PHP+Security

You'll get 100 million hits, but the first page or two are all that matter to an informed software developer.

Best regards, ~Ray
0
 
HagayMandelCommented:
What is $preChorusQ?, where do you define itor get it from?
This should contain  the actual input.
0
 
Amar BardoliwalaCommented:
Hello Solutionabc,

You should also give your function filter_var()  as well as all variables that you are passing in it.. only than someone here will be able to help you.

Thanks.

Amar.
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
HagayMandelCommented:
If you want to check a single digit, then use:
<?php
$var=9; //Or any variable or other source
if ($var>=0 and $var<=9) {
      print('OK'); //Optional
}
else {
      die('Input problem!!!');
}
 ?>

For checking an array of digits, use:

<?php

$var=array(0=>1,1=>1,2=>2,3=>12,4=>4,5=>4);//Put your array
for ($i=0; $i<=count($var);$i++){
if ($var[$i]>=0 and $var[$i]<=9) {
      print('OK<br />');//Optional
}
else {
      die('<b>Input problem</b>, digit #'.$i. ' ('.$var[$i] .'), is not in scope!');
}
}
 
?>
0
 
Rok-KraljCommented:
Just don't complicate.
$input='23';

if (ctype_digit($input)) {
die('Please enter a number.');
} else if (int($input)<0 or int($input)>9) {
die('Please enter a number between');
} else {
echo 'OK!';
}

Open in new window

0
 
Rok-KraljCommented:
I made a mistake, forgot negation (!)
$input='23';

if (!ctype_digit($input)) {
    die('Please enter a number.');
} else if (int($input)<0 or int($input)>9) {
    die('Please enter a number between 0 and 9.');
} else {
    echo 'OK!';
}

Open in new window

0
 
Ray PaseurCommented:
Hi, @Solutionabc:

It's very useful to print out the values of the numbers you are trying to test.  Please see the code snippet for an example of how to do that.

Also, it looks like the code you posted, admittedly incomplete, might depend on a deprecated (OLD-DO NOT USE) feature of PHP called "register_globals."  You might be getting the variable named "$preChorusQ" from some external input like a POST array?
http://www.php.net/manual/en/security.globals.php

HTH, ~Ray
<?php // RAY_temp_Solutionabc.php
error_reporting(E_ALL);

// THIS PART IS ADDED SO WE CAN DEMONSTRATE HOW TO TEST
$preChorusQ = 'A3'; // STRING
// $preChorusQ = 3;   // INTEGER
var_dump($preChorusQ);

// THIS PART IS FROM THE POST AT EE
$int_preChorusQ = array("options"=>
array("min_range"=>0, "max_range"=>9));

if (!filter_var($preChorusQ, FILTER_VALIDATE_INT, $int_preChorusQ)){
die('The quantity you entered is not valid');
}

Open in new window

0
 
Ray PaseurCommented:
Also, it is a little off topic, but you will find your code easier to understand, modify and debug if you use some "coding standards" that line up the variable assignments and control structures.  I might write the code you posted like this - identical meaning, but maybe a little easier to understand.  The exact choice of coding standards is not as important as consistent application.  

The use of error_reporting(E_ALL); is VERY USEFUL, too!

Best of luck with your project, ~Ray
<?php // RAY_temp_Solutionabc.php
error_reporting(E_ALL);


// THIS PART IS IDENTICAL BUR REFORMATTED FROM THE POST AT EE
$int_preChorusQ = array
( "options" => array
    ( "min_range"=>0
    , "max_range"=>9
    )
)
;

if (!filter_var($preChorusQ, FILTER_VALIDATE_INT, $int_preChorusQ))
{
    die('The quantity you entered is not valid');
}

Open in new window

0
 
SolutionabcAuthor Commented:
I'm confused, Ray are you saying that using the POST array to pass information is an old do not use method for passing info?
0
 
Ray PaseurCommented:
No, not saying that at all - the POST method populates the $_POST array.  But it should not accidentally inject a variable into your namespace!

Read that information about globals and security on the PHP web site.  
http://www.php.net/manual/en/security.globals.php

In the "olden days" PHP did some automatic things that were well-intentioned, one example here:

If $_POST contained a field named 'xyz', then PHP created a new variable named $xyz.  This "variable injection" was supposed to make life easier but in reality it opened up a host of security issues.  So today, we set "register_globals" to "off" and simply look at $_POST["xyz"] to find the posted data.
0
 
SolutionabcAuthor Commented:
ok so I tried the var_dump and prechorusQ = 0.

It is correctly passing the value into the variable but I want it to be able to accept 0 without it calling the die().

how would I adjust the min value?

thanks.
0
 
Rok-KraljCommented:
Why do you insist on filter_var, which should be deprecated in my opinion?
$input=$preChorusQ;

if (!ctype_digit($input)) {
    die('Please enter a number.');
} else if (int($input)<0 or int($input)>9) {
    die('Please enter a number between 0 and 9.');
} else {
    echo 'OK!';
}

Open in new window

0
 
SolutionabcAuthor Commented:
I though using that php filter is the best way to validate the int and protect from sql injection?
0
 
Ray PaseurCommented:
Part of the decision process must deal with whether to accept a string like ' 1 ' to be the same as '1' - this is accommodated in the trim() function.

PHP function filter_var() was introduced at PHP 5.2.  Interesting note on this page:
http://us3.php.net/manual/en/filter.filters.validate.php
"Numbers +0 and -0 are not valid integers but validate as floats."

So it might be more useful for validating a data base auto_increment key.

This alternative seems to work OK and includes zero, but would fail -0.
<?php // RAY_temp_Solutionabc.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

// THIS PART IS IDENTICAL BUT REFORMATTED FROM THE POST AT EE
$int_preChorusQ = array();
$int_preChorusQ['options']['min_range'] = 0;
$int_preChorusQ['options']['max_range'] = 0;
$int_preChorusQ['flags'] = NULL;

// TEST CASE
$preChorusQ = 0;
if (!filter_var($preChorusQ, FILTER_VALIDATE_INT, $int_preChorusQ))
{
    echo "The value $preChorusQ is not acceptable";
}



// ALTERNATIVE
function clean_digit($x)
{
    $x = trim($x);
    if (preg_match('/^(\d){1}$/', trim($x))) return $x;
    return FALSE;
}

$n = -1; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  0; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  1; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  2; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  3; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  4; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  5; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  6; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  7; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  8; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n =  9; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = 10; echo PHP_EOL . $n; var_dump(clean_digit($n));

$n = ' 0'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 1'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 2'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 3'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 4'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 5'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 6'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 7'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 8'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = ' 9'; echo PHP_EOL . $n; var_dump(clean_digit($n));
$n = '10'; echo PHP_EOL . $n; var_dump(clean_digit($n));

$n = '1X'; echo PHP_EOL . $n; var_dump(clean_digit($n));

Open in new window

0
 
Ray PaseurCommented:
Sorry - delete line 23 in the code snippet - redundant.
0
 
SolutionabcAuthor Commented:
I don't really have to worry about ' 1' (the string) because it will not allow 2 characters in the user input box only one. and even if they modify the input box to accept more characters it won't make sense to the users and it will get declined.

but I should use the trim() so that it takes only the first integer as a safety precaution.

if I trim to only use the first ineger and confirm that the posted variable is of type int() is that good enough to protect against sql injection?

thanks for your great information!
0
 
Rok-KraljCommented:
@Solutionabc: I though using that php filter is the best way to validate the int and protect from sql injection?

You thought wrong.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.