(Basic Question) PHP Injection?

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
phpGamer
Forum Newbie
Posts: 5
Joined: Tue Aug 25, 2009 11:12 am

(Basic Question) PHP Injection?

Post by phpGamer »

Hi I am very new to programming and PHP in general so I apologize in advance if the question is too trivial or obvious.

So the question is how to prevent SQL and PHP injection by validating inputs. Now it is pretty simple for me to construct input validator:

Code: Select all

 
<?php
 
/*
    Input Cleaning
    Returns clean input
*/
 
// CLEAN INTEGERS
function inputVerifyIntegers($intSent,$numDigits) {
    $intCheck1 = (string)substr(htmlentities($intSent,ENT_QUOTES),0,$numDigits);
    return (integer)preg_replace('/[^0123456789]*/','',$intCheck1);
}
 
// CLEAN ALPHANUMERIC
function inputVerifyAlpha($alphaSent,$numLetters) {
    $alphaCheck1 = (string)substr(htmlentities($alphaSent,ENT_QUOTES),0,$numLetters);
    return (string)preg_replace('/[^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]*/','',$alphaCheck1);
}
 
?>
 
Now the question is what stops some creative input for $intSent for example something like

Code: Select all

){}function evil(){return evilValue;}function($e
now, evil input has been returned. Is this impossible in PHP due to PHP only interpreting one line? Also are there any serious problems with my whitelist/code? What stops hackers from inserting tons of lines of code, merely the fact that PHP interprets only one line per expression or the fact your code is secret? Also I see several potential casting problems. Should I enclose the casts in some kind of exception handling in case they fail? Again sorry if they seem so trivial. Thanks.
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: (Basic Question) PHP Injection?

Post by yacahuma »

for simple things use
ctype_alpha()
ctype_digit()
ctype_alnum()
ctype_lower()
ctype_upper()

for complex data(like phone numbers, emails) use
preg_match()
Post Reply