Solved

php validate number

Posted on 2010-08-27
17
234 Views
Last Modified: 2012-05-10
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

0
Comment
Question by:Solutionabc
  • 6
  • 4
  • 4
  • +2
17 Comments
 
LVL 16

Expert Comment

by:HagayMandel
Comment Utility
What is $preChorusQ?, where do you define itor get it from?
This should contain  the actual input.
0
 
LVL 11

Expert Comment

by:Amar Bardoliwala
Comment Utility
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
 
LVL 16

Expert Comment

by:HagayMandel
Comment Utility
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
 
LVL 12

Expert Comment

by:Rok-Kralj
Comment Utility
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
 
LVL 12

Expert Comment

by:Rok-Kralj
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 

Author Comment

by:Solutionabc
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 

Author Comment

by:Solutionabc
Comment Utility
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
 
LVL 12

Expert Comment

by:Rok-Kralj
Comment Utility
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
 

Author Comment

by:Solutionabc
Comment Utility
I though using that php filter is the best way to validate the int and protect from sql injection?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Sorry - delete line 23 in the code snippet - redundant.
0
 

Author Comment

by:Solutionabc
Comment Utility
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
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
"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
 
LVL 12

Expert Comment

by:Rok-Kralj
Comment Utility
@Solutionabc: I though using that php filter is the best way to validate the int and protect from sql injection?

You thought wrong.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now