I needed a generic function in php
that will properly clean and escape any variable used in a Dynamic MySQL Statement. For example MySQL is vulnerable to random user - inserted data. Any sample code , or links are highly appreciated.
Edit 1- I did follow the links posted below. I still feel a concrete example would help.The requirement at work is to have a function which ma look like below:
function MySQLClean($string){
// Contentns
return string;
}
My questions are
' ^
etcAn example of a Before and After "Escaping and Cleaning" the query string will be highly appreciated.
If this explanation seems vague and unspecific - that pretty much sums up my understanding of how to clean and validate the data. I will however be glad to provide any further details.
Edit 2
- After reading some material on the net and following the link in the given below answers - I have the below following function
function MySQLClean($string)
{
if(get_magic_quotes_gpc()){
$string = stripslashes($string);
}
return addcslashes(mysql_real_escape_string($string),"%_");
}
Is this sufficient?
Ok, since you've edited your question and I better understand what you're trying to do, let me say this:
Don't Do It!
You will run into problems with the character set of the connection, differing collations, etc. There are a fair number of edge cases that you will likely miss and still be vulnerable with. For one example of an edge case, check out Chris Shiflett's Blog Post...
If you're writing a DB abstraction layer and want to create a uniform interface, call the database's escape method in the driver layer. Don't try to write your own escape mechanism since it will not be nearly as good as the in-built one, and will not be kept up to date as well either...
If you use prepared statements, your data will be cleaned and help prevent SQL injection attacks.