在没有mysql_real_escape_string的情况下清理联系表单 [英] Sanitize contact form without mysql_real_escape_string
问题描述
在将表单输入存储到数据库之前,我通常使用此函数对表单输入进行清理:
I normally use this function to sanitize my form inputs before storing them into my database:
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
直到今天,我仍未意识到 mysql_real_escape_string
需要数据库连接,因为我仅在清理数据之前才使用它,然后再将其存储到数据库中。
Until today I didn't realize that mysql_real_escape_string
required a database connection as I've only used it when I've been cleaning the data before storing it into the database.
我尝试在联系表单上使用该功能,并收到无法建立到服务器的链接错误。我可以连接到数据库,但是没有必要,因为我只是想先清理掉数据,然后再通过联系表将其发送到我的电子邮件中。
I tried using the function on a contact form and got the "A link to the server could not be established" error. I could connect to the database but there is no need because I simply am trying to sanitize the data before it's being sent out to my e-mail via the contact form.
清理未存储在mysql数据库中的数据的最佳方法是什么?是否仍需要清理这些数据?
What is the best way to sanitize data that's not being stored in a mysql database and does this data still need to be sanitized?
推荐答案
使用 filter_var()
http://php.net/manual/zh-CN /function.filter-var.php
就像您要清理电子邮件一样:
like if you want to sanitize an email:
$_POST['email'] = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
到消息
$_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
是英语
这篇关于在没有mysql_real_escape_string的情况下清理联系表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!