HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

String sanitisation function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sanitisationfunctionstring

Problem

I have a search function on my website. In addition, elsewhere I have a place where users can submit categories for their posts. I want the categories to have an uppercase first letter and the rest lower case. I know there far more complex ways to secure a user input string, but do you think that as a fairly basic function, this is relatively secure?

function purify_string($string){
       $script_tags = "/\+/i";
       $string = strip_tags(addslashes($string));   
       $string = preg_replace($script_tags, '', $string);
       $string = trim($string); 
       $string = strtolower($string);
       $string = ucfirst($string);     
       return $string;
     }

Solution

Instead of trying to purify the category for the user, which may or may not have unexpected results, you should simply reject everything that does not conform to your level of standard, and let the user fix it:

function isValidCategoryName($string) {
    return preg_match("/^[A-Z][a-z0-9 ]+$/", $string);
}


If it doesn't match, prompt the user with an error message and tell him to try again. Your job isn't to try to extract a good category from a bad one.

At most you could just correct the case with ucfirst if you want.

Code Snippets

function isValidCategoryName($string) {
    return preg_match("/^[A-Z][a-z0-9 ]+$/", $string);
}

Context

StackExchange Code Review Q#54382, answer score: 4

Revisions (0)

No revisions yet.