?
Solved

php validate number

Posted on 2010-08-27
17
Medium Priority
?
246 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
  • 4
  • +2
17 Comments
 
LVL 16

Expert Comment

by:HagayMandel
ID: 33548022
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
ID: 33548304
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
ID: 33548742
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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 
LVL 12

Expert Comment

by:Rok-Kralj
ID: 33548839
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
ID: 33548840
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 111

Expert Comment

by:Ray Paseur
ID: 33549282
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 111

Expert Comment

by:Ray Paseur
ID: 33549295
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
ID: 33553021
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 33553241
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
ID: 33553965
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
ID: 33554077
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
ID: 33554524
I though using that php filter is the best way to validate the int and protect from sql injection?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 33554544
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 111

Expert Comment

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

Author Comment

by:Solutionabc
ID: 33554707
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 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 33554737
"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
ID: 33557046
@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

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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.
Suggested Courses

770 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