PHP: new 3 functions now used to sterilize, sanitize & escape quote from string [tested]

0
135
sterilize sanitize escape quote
sterilize sanitize escape quote

this function is best ever string sanitizer in php
while collecting information from form have been everyday need because of the transactional needs of some application

so while or before validating the inputs from our forms will need a security measures that escape injection of hackers code into our file system

Using explode and implode

we used php explode and implode function in order to find the array of special characters and remove them after which we finally convert it back to string using the function respectively accordingly

 
<?php
function sanitize($string) {
$arr = array();
$string = preg_replace("/[^a-zA-Z0-9\']/", " ", $string);
$delimiters = array('@','#','$','%','^','&','*','/','\ ','[',']','{','}','|','(','_','-','+','=','`','¬','!',')',';','"','<','>',",",".",':',"?",'\n',"'");

$delimiterscount = count($delimiters);
for ($i=0; $i<$delimiterscount; $i++) {
$string = preg_replace("/\s\s+/", ", ", str_replace(str_replace(" ",'',$delimiters[$i]), ', ', $string));
}
$string = explode(",",str_replace(" ", ",", $string)); // Remove the str_replace to make it contain two words in a row

foreach($string as $val){
	if(!empty($val) && strlen($val)>0){
			$arr[] = stripslashes($val);
	}
}

return implode($arr);

}
?>

the limitations

the limitation of this function is it inability to consider spaces in sentences while being used and unable to replace any replaced / removed character with acceptable machine code.

let’s see how it output result and easily apply it to our job.

 <?php
$myname = 'G~#o£~  #d&w  ,i-£n';
$myname = sanitize($myname);
echo $myname;

?>

this function below was normally used before the above 3 functions

it uses trim and convert html characters to special characters (only use this if you wish to store html as it was input by the user) it does not remove invalid characters
rather it removes only html tags

it is not advisable to use same below codes today because it can give inaccurate data that might contain special characters which may assist hackers to hack into your codes easily.

see it below

the code working but not in use as in generally accepted anymore

 <?php
function clean($string){
	$string = strip_tags($string); // Remove HTML
	$string = htmlspecialchars($string); // Convert characters
	$string = trim(rtrim(ltrim($string))); // Remove spaces
	return $string;
}
?>
<?php
$myname = 'G~#o£~<p>  #d&w  ,i-£n';
$myname = clean($myname);
echo $myname;

?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here