zaterdag 16 februari 2013

Filtering userinput for outputting filenames in PHP

So you have a string, want to turn it into a legit filename, or just display the string in html compatible mode?

if (!function_exists("filesystemcode")){

function filesystemcode($string, $arr1="a", $arr2="b") {
$c=array();
if (isset($arr1)) {
if (!isset(${$arr1}) || !is_array(${$arr1})){
${$arr1} = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
}}

if (isset($arr2)) {
if (!isset(${$arr2}) || !is_array(${$arr2})){
${$arr2} = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");}else{$b='';}
}
if (isset($a) && isset($b)){
return str_replace($a, $b, $string);
}else{return($string);}

}
}


Remove html compatible encoded illegal filename characters:

//$string="%21dad";
$string=filesystemcode($string, "a", "c");
//echo $string; //"dad";



Remove illegal filename chars:

//$string="/dad";
$string=filesystemcode($string, "b", "c");
//echo $string; //"dad";




Convert filesystem incompatible chars into html compatible chars:

//$string="!dad";
$string=filesystemcode($string, "b", "a");
//echo $string; //"%21dad";




Convert html compatible chars into filesystem incompatible chars:

//$string="%21dad";
$string=filesystemcode($string, "a", "b");
//echo $string; //"!dad";



Note, usually you would want to urlencode($string) afterwards.

Geen opmerkingen:

Een reactie posten