Safety test data in PHP for SQL [closed]
What are the tests to do when you receive an id or a string in POST / GET?
EDIT : it's actually to fill a database sql, sorry.
EDIT 2 : here are the tests and the filters I use.
For an id :
if (isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id']))
$id = trim($_GET['id']);
For a string :
if (isset($_GET['string']) && !empty($_GET['string']) && is_string($_GET['string']))
$str = mysql_real_escape_string(stripslashes(trim($_GET['string'])));
Wha开发者_如何学JAVAt do you think ?
The first rule of testing data is to validate it, and make sure it is what you want/need it to be. If it's supposed to be an email, then make sure it's an email. If you need it to be a phone number, then you can use preg_* functions to match the phone number patterns for your local area (or the area you expect to use the form the most).
If it's just meant to be a basic amount of text, then you'll need to sanitize it. The Security module in the Joomla! code base has an excellent text sanitization function that does loads for preventing XSS attacks and the like.
If it's supposed to be an id number (say, of a user) then you can (and should) use phps built-in function is_numeric().
Outside of that, if you use something like PDO or MySQLi with prepared statements, the database server will work with PHP to make sure all your text is sanitary and won't break the database.
This is a good read to sanitize and filter variables from POST, GET:
http://www.phpro.org/tutorials/Filtering-Data-with-PHP.html
精彩评论