Well... first, the function's name -- "Secure" -- is much too ambiguous. There are various kinds of security. When you use a value in HTML, you secure it with htmlspecialchars. When you use a value in SQL, you secure it with prepared statements or mysql_real_escape_string. What you're trying to do looks to me like form validation, and if part of that validation requires that a value contain only alphabetic characters, then you can use the ctype_alpha function.
When it comes to security, it's rarely a good idea to "re-invent the wheel". PHP has some pretty good filtering functions. I would definitely check them out as they will be more secure than your custom functions.
If your aim in this case is to remove all non-alpha characters:
PHP Code:
return preg_replace('/[^a-zA-Z]/', '', $str);
However, in most cases it's better to simply validate that the field contains the correct type of data and if not return an error to the user, rather than assume you know what they meant to type in and silently change it without the user being given a chance to correct it (see the aforementioned ctype_alpha() in this case).
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Ok, you "shouldn't" do this, since you shouldn't ever change the original raw data and you "should" store the raw data in the database as well.
That asside... i would rather use a "whitelist" instead of a "blacklist".
If you escape the data when you need to, you can often forget! However, if you have to unescape the data instead when you need to (rarely), the errors of not doing so when you forget are usually much much less! This is why i tend to:
1. Iterate over the $_POST, $_GET, $_REQUEST, $_COOKIE, etc super globals (remember some may be multi dimention arrays if the forms name='dsdsa[]')
2. Run htmlentities(..., ENT_QUOTES) followed by mysql_real_escape_string(). Make sure mysql escaping is AFTER htmlentities else you will suffer from double slashes!
3. The data can now be safely shown on site OR used in the database! No need to remember to escape anything, instead, you just need to unescape it (reverse the order) on the few occassions that you need to (such as using variables in URLs). Also, data can instantly be shown from the database without needing to escape it first (because htmlentities was already run on it) to prevent attacks such as XSS.
Hope that helps.
Kind regards,
Scott
P.S. If showing the data in URL's onsite you will need to unescape it, then use rawurlencode() instead.
Bookmarks