PHP
Useful functions
- Using
mysql_real_escape_string()around each variable prevents SQL Injection. This example demonstrates the “best practice” method for querying a database, independent of the Magic Quotes setting.<?php // Quote variable to make safe function quote_smart($value) { // Stripslashes if (get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote if not a number or a numeric string if (!is_numeric($value)) { $value = "'" . mysql_real_escape_string($value) . "'"; } return $value; } // Connect $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error()); // Make a safe query $query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s", quote_smart($_POST['username']), quote_smart($_POST['password'])); mysql_query($query); ?>
The query will now execute correctly, and SQL Injection attacks will not work.
* Convert all applicable characters to HTML entities
htmlentities
* Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.
urlencode(); rawurlencode()