PHP Input Checking

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have a HTML form where the user can type in certain values, but I
only want them to able able to submit integers (0-9). I post to a PHP
page with the following "snippit" of code (all the variables have been
properly assigned):

// Checks for illegal chars
$illegal_chars = array("`", "~", "!", "@", "#", "$", "%", "^", "&",
"*", "(", ")", "-", "_", "=", "+", "q", "w", "e", "r", "t", "y", "u",
"i", "o", "p", "[", "{", "]", "}", "\", "|", "a", "s", "d", "f", "g",
"h", "j", "k", "l", ";", ":", "'", "\"", "z", "x", "c", "v", "b", "n",
"m", ",", "<", ".", ">", "/", "?");
foreach ($illegal_chars as $value) {
    if (stripos($db_mysql, $value)) { $pass1 = "f"; }
    elseif (stripos($db_postgre, $value)) { $pass2 = "f"; }
    elseif (stripos($db_oracle, $value)) { $pass3 = "f"; }
    elseif (stripos($email_basic, $value)) { $pass4 = "f"; }
    elseif (stripos($email_exchange, $value)) { $pass5 = "f"; }
    elseif (stripos($ftp_users, $value)) { $pass6 = "f"; }
    elseif (stripos($domain_subdomains, $value)) { $pass7 = "f"; }
    else {}

The code will not work, and I can't see why. The variables $pass1-pass7
aren't set after the foreach() loop, no matter what is in the input!

Any ideas?


Re: PHP Input Checking

Kingo said the following on 26/04/2006 23:13:
Quoted text here. Click to load it


There's a whole host of simple one-liners that will achieve this.  
Casting the variable to an int would be one way to guarantee that the  
result is an integer.  Use of is_numeric() would be a way to check  
whether the value is an integer.  ctype_digit() would be another.

NOTE: Although I don't know how you're using $pass1 -> $pass7, you're  
probably much better off using an array, i.e. $pass[1] -> $pass[7], and  
setting them to boolean FALSE rather than "f".


Re: PHP Input Checking

I tried to use is_numeric(), but it supports more than just 0-9. All I
want to check is if the input has only the characters 0-9 in it. I'm
guessing from the examples in the PHP manual that ctype_digit() would
be the best way to go here?

Re: PHP Input Checking

function my_integer_check($data, $length = 1)

if(strten($data) > $length){
    return false;


    return is_numeric($data);


Re: PHP Input Checking

Okay, I've got it working using is_numeric(), and then a conditional

Thanks for your inputs!

Excuse my shocking PHP knowledge!!


Re: PHP Input Checking

Kingo wrote:

Quoted text here. Click to load it

Have you tried using a regex?

if (preg_match($string,'/\D/') > 0) {
    // contains illegal characters

Replace $string with the string variable you want to check. The \D
means any character that isn't a decimal digit, which is probably what
you want to check the string for.

Kim André Akerø
(remove NOSPAM to contact me directly)

Site Timeline