Sanitize input from forms or database with php
Very often a website developers has to deal with user input, and if not sanitized properly could break the code or insert malicious code into your database.
By creating customised functions, a website developer’s job, could be made a lot easier and it’s very handy for doing updates to your code.
This function is something I designed, and will allow you to sanitize your input either coming from a form on your website or a database table before doing anything with it like send an email, display it on the website or do an update / insert to a db table.
//function to sanitise user input
//preventing sql errors and code breaking
// [1] = numbers
// [2] = small letters
// [3] = caps letters
// [4] = other characters that are included between the [4 ] brackets (e.g. [4.,@-_ ])
//notice last gap for spaces
// ' " \ / needs a \ in front like : \' and \" and \\ and \/
function ewd_sanitize($input, $format){
if($input == ""){
return;
}else{
//prepare characters to be kept
$ewd_keep = '#[^';
$ewd_keep .= stristr($format,'[1]') ? '0-9' : '';//allow digits
$ewd_keep .= stristr($format,'[2]') ? 'a-z' : '';//allow small letters
$ewd_keep .= stristr($format,'[3]') ? 'A-Z' : '';//allow caps letters
//other
if(stristr($format,'[4')){
$pattern = "/(\[4)(.*?)(\])/"; //match the 4th bracket and get the characters
preg_match($pattern, $format, $matches);
$ewd = $matches[2];
$ewd_keep .= stristr($ewd,' ') ? ' ' : '';//allow spaces
$ewd_keep .= stristr($ewd,'.') ? '\.' : '';//allow dot
$ewd_keep .= stristr($ewd,'@') ? '@' : '';//allow @ symbol
$ewd_keep .= stristr($ewd,'"') ? '\"' : '';//allow "
$ewd_keep .= stristr($ewd,"'") ? "\'" : '';//allow '
$ewd_keep .= stristr($ewd,'-') ? '\-' : '';//allow - dash
$ewd_keep .= stristr($ewd,'_') ? '\_' : '';//allow _ underscore
$ewd_keep .= stristr($ewd,'(') ? '\(' : '';//allow ( open bracket
$ewd_keep .= stristr($ewd,')') ? '\)' : '';//allow ) closing bracket
$ewd_keep .= stristr($ewd,'\\') ? '\\\\' : '';//allow \
$ewd_keep .= stristr($ewd,'/') ? '\/' : '';//allow /
}
$ewd_keep .= ']#';
$input = preg_replace($ewd_keep,'',$input);
}
return $input;
}
Example how to use it in your code:
//this will allow most characteres
echo ewd_sanitize("checking this text(123) @. O'Connel \/", "[1][2][3][4@.-()\'\\\\/ ]");
//numbers only
echo ewd_sanitize("checking this text(123) @. O'Connel \/", "[1]");
//small letter only
echo ewd_sanitize("check this Out 123","[2]");
//all letters and numbers
echo ewd_sanitize("check this Out Now 123","[1][2][3]");
//allow an email
echo ewd_sanitize("info@domain-name.com","[1][2][3][4@.-_]");
Tags: sanitize input received
This entry was posted
on Thursday, November 1st, 2007 at 4:42 pm and is filed under PHP.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.
















