I just had this idea of "preSecure" all userinput data from $_post and $_get. But I was wondering if this is good practice and would like some input on this. Here is what I came up with:
function clean_str($str){
return preg_replace('#[^a-z_ 0-9@.-]#i', '', $str);
}
if ($_POST){
foreach ($_POST AS $key => $val){
$_POST[$key] = clean_str($val);
}
}
if ($_GET){
foreach ($_GET AS $key => $val){
$_GET[$key] = clean_str($val);
}
}
This snippet would simply be run at the beginning of each http request. The clean_str function can be developed to allow other chars and replace characters etc (this is just an example). But I think the first goal are to simply prevent sql injection. The only bad thing I can see with this approach right now is if your "plugin" need to send sql commands from user input. The appraoch above could we wrapped in a function of course and be called if needed. Post and Get are global vars so that would not be a problem.
I'm actually writing my own framework (still a lot of work) that I will release if I ever be able to finish it. The thing is that I often see novice developers add $_POST['userinput'] inside database queries. The code above should make even that okay. Well that was some background of what I'm up to and why I bring this up.
I would be very happy to hear your thoughts. This might not be the best question for Stack Overflow, I suppose I want to open more like a discussion to this approach to share thoughts and inputs. But to formulate my question(s) to this, it would be something in line with: Are there any other approaches that would be faster or more scalable than this, or is equal to this, or can another function complement this approach? Is this approach good practice? Is it okay to overwrite the global vars of post and get data like above?
I know the code above is not object oriented, but it's about the approach of cleaning the users' input datas automatically before running checks on them. I think this will save a lot of code and headaches.
Please share your thoughts with me. As comments are limited here on Stack Overflow, I would appreciate if you reply as answers if you bring new thoughts to this table. Comments are to comment on specific thoughts/answers in this case.