2014-09-24, 01:15 PM
I saw in "functions_forumlist.php" file (MyBB 1.8) this line of code:
So, what's the best method for sanitizing a variable in the following conditions?
1) may contain only these characters: A-Z, a-z, 0-9, trailing slash, whitespace, minus sign and underscore
2) replace all multiple trailing slashes with a single one
3) check if the first character is a trailing slash and remove it
4) check if the last character is a trailing slash and remove it
5) finally, display a warning if the variable contain at least one whitespace
This is how I do it (a basic example, a bit different from what I saw in "functions_forumlist.php" file) and it works.
However, could someone check my code please? I have a feeling that it's not the best way!
Any advice you can provide me would be appreciated. Thank you.
// Sanitize name and description of forum.
$forum['name'] = preg_replace("#&(?!\#[0-9]+;)#si", "&", $forum['name']);
Now, I'm working on a plugin and ... I need something similar. That's why I'm asking for a little help.So, what's the best method for sanitizing a variable in the following conditions?
1) may contain only these characters: A-Z, a-z, 0-9, trailing slash, whitespace, minus sign and underscore
2) replace all multiple trailing slashes with a single one
3) check if the first character is a trailing slash and remove it
4) check if the last character is a trailing slash and remove it
5) finally, display a warning if the variable contain at least one whitespace
This is how I do it (a basic example, a bit different from what I saw in "functions_forumlist.php" file) and it works.
However, could someone check my code please? I have a feeling that it's not the best way!
// $var
$var = '///bla_bla//=-.%8*!|_=/';
// if '$var' is NOT set or is empty
if(!isset($var) || empty($var))
{
// set a default name
$var = 'default_name';
}
else // attempt to sanitize '$var'
{
// use only: A-Z, a-z, 0-9, trailing slash, whitespace, minus sign and underscore
$var = preg_replace('|[^A-Za-z0-9\s\/\-\_]|', '', $var);
// replace all multiple trailing slashes with a single one
$var = preg_replace('~/+~', '/', $var);
/*
or better, in a single line (!!!?):
$var = preg_replace('~/+~', '/', preg_replace('|[^A-Za-z0-9\s\/\-\_]|', '', $var));
*/
// check if the first character is a slash and remove it
if(substr($var, 0, strlen('/')) == '/')
{
$var = substr($var, strlen('/'));
}
// check if the last character is a slash and remove it
if(substr($var, -1) == '/')
{
$var = substr($var, 0, -1);
}
// output a message if there is at least one whitespace
if(preg_match('/\s/', $var))
{
echo "This variable contain at least one white space./n";
}
}
// output $var
echo $var; // result is: bla_bla/-8|_
Any advice you can provide me would be appreciated. Thank you.