First, establish a security abstraction layer
We do not recommend that you manually apply the techniques described previously to each user input instance, but strongly recommend that you create an abstraction layer for this purpose. A simple abstraction is to add your validation scheme to a function, and call this function for every item that the user enters. Of course, we can also create a more complex, higher level of abstraction-encapsulating a secure query into a class to apply to the entire application. There are already many of these free classes on the Web, and we are going to discuss some of them in this article.
There are at least three advantages to doing this abstraction (and each will improve the security level):
1. Localized code.
2. Make the query structure faster and more reliable-because it can be done in part by abstract code.
3. When built on security features and properly used, this will effectively prevent the various injection attacks we discussed earlier.
Ii. Improving existing applications
If you want to improve an existing application, it is most appropriate to use a simple abstraction layer. A function that can simply "clean up" any user input that you collect may look like the following:
function safe( $string ) {
return "'" . mysql_real_escape_string( $string ) . "'"
}
"Note" We have constructed single quotes and mysql_real_escape_string () functions corresponding to the value requirements. Next, you can use this function to construct a $query variable, as follows:
$variety = safe( $_POST['variety'] );
$query = " SELECT * FROM wines WHERE variety=" . $variety;
Now, your user is trying to do an injection attack-by entering the following as a variable $variety value:
lagrein' or 1=1;
Note that if the above cleanup is not done, the final query will look like this (this will result in unpredictable results):
SELECT * FROM wines WHERE variety = 'lagrein' or 1=1;'
Now, however, since the user's input has been cleaned up, the query statement becomes one of the following harmless forms:
SELECT * FROM wines WHERE variety = 'lagrein\' or 1=1\;'
Since there is no variety field in the database corresponding to the specified value (which is exactly what the malicious user entered-lagrein ' or 1=1;), the query will not return any results and the injection will fail.