It's even more simple. Just htmlspecialchars()
(with quote style and character set) on user-controlled input is enough. The strip_tags()
is only useful if you already want to sanitize data prior to processing/save in database, which is often not used in real world. HTML code doesn't harm in PHP source, but PHP code may do so if you use eval()
on non-sanitized user-controlled input or that kind of evil stuff.
This however doesn't save you from SQL injections, but that's another story.
Update: to get clean user input from the request to avoid magic quotes in user-controlled input, you can use the following function:
function get_string($array, $index, $default = null) {
if (isset($array[$index]) && strlen($value = trim($array[$index])) > 0) {
return get_magic_quotes_gpc() ? stripslashes($value) : $value;
} else {
return $default;
}
}
which can be used as:
$username = get_string($_POST, "username");
$password = get_string($_POST, "password");
(you can do simliar for get_number
, get_boolean
, get_array
, etc)
To prepare the SQL query to avoid SQL injections, do:
$sql = sprintf(
"SELECT id FROM user WHERE username = '%s' AND password = MD5('%s')",
mysql_real_escape_string($user),
mysql_real_escape_string($password)
);
To display user-controlled input to avoid XSS, do:
echo htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…