r/PHPhelp • u/nisebblumberg • Nov 10 '22
Thoughts on sanitizing strings? (Intended for internal usage)
I have an internal usage database system I am developing and I'm running this function for input strings to ensure against injections and cross-site scripting. I also have the connector to the database with the inability to DROP or delete data, but updates are possible. I'm just wondering if this is alright, or am I just being too paranoid?
function sanitizestring($string){
$stringnew=str_replace(';','',$string);
$stringnew=strip_tags($stringnew);
$stringnew=filter_var($stringnew,FILTER_SANITIZE_STRING);
$string=$stringnew;
return $string;
}
5
Upvotes
10
u/allen_jb Nov 10 '22 edited Nov 10 '22
This function is horribly horribly wrong and will corrupt your data in unfixable, hard to debug (for anyone who doesn't know this is there) ways.
You should only sanitize (or rather escape) data for the exact method you're currently outputting to. Sanitize for HTML in your views.
To prevent SQL injection, use prepared queries (AKA parameterized queries). See the examples on https://www.php.net/manual/en/pdo.prepare.php (mysqli can also do this).
(Also, FILTER_SANITIZE_STRING is deprecated from 8.1. Use htmlspecialchars() or whatever your templating / view library provides instead)
5
u/__adrian_enspireddit Nov 10 '22 edited Nov 10 '22
+1 for allen's comments.
DO NOT EVER write a "sanitize" function that aims to fix all possible problems at once. Always address each problem on its own and mind context.
specifically,
strip_tags() is a completely broken function. in general, don't use it.
A good Rule of Thumb is that if you're thinking the word "sanitize," you're probably doing it wrong. Instead, think in terms of input validation, parameterization, escaping, and encoding.
4
u/kAlvaro Nov 10 '22
Just yesterday I heard a security consultant stating that you absolutely need to sanitise user input and strip anything that resembles HTML tags and JavaScript code from the input before you store it in the database, and that you cannot trust the application that consumes database information to do the right thing when rendering HTML. I don't want to pontificate against experts in something that isn't my area of expertise, but that sounded so wrong to me at so many levels...
I always stick to two simple rules:
All those functions are excellent at breaking #1 and do little to enforce #2.
0
u/Twinsen343 Nov 10 '22
I use https://github.com/farisc0de/phpsanitization and it's amazing.