# String sanitisation function

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 = "/\<script +(.+)<\/script>+/i";
$string = strip_tags(addslashes($string));
$string = preg_replace($script_tags, '', $string);$string = trim($string);$string = strtolower($string);$string = ucfirst($string); return$string;
}


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. • Many thanks. Simple approach to what could become a complex problem – GhostRider Jun 16 '14 at 18:56 Judging from your phrase "ways to secure an input string", I suspect you may have a misconception about security. A string contains data, and it makes no sense to call a string "secure" or "insecure". Rather, security depends entirely on what your code does with the string. As extreme hypothetical examples, • $string might be '<script type="text/javascript">doSomethingNasty()</script>', and it would be no big deal as long as your code handles it correctly. Proper use of escaping functions, such as calling htmlspecialchars() when outputting it in HTML context, is the key. The fact that you're reading this answer right now, and your browser is not doingSomethingNasty(), is an illustration of these principles. It's perfectly safe to render a <script> tag without any kind of censorship, as long as escaping is applied correctly.
• On the other hand, it would be totally unsafe if system($string); appears in your code, even if $string might contain something purely alphabetic, such as 'reboot'.

<?php echo htmlspecialchars($something); ?>  instead of just <?php echo$something; ?>

• Validation / sanitization is for enforcing business rules, not security. You want an uppercase initial, followed by all lowercase, for consistency and aesthetic reasons. You can enforce such a rule if you want — the easiest way is ucfirst(strtolower(trim(\$string))).