简体   繁体   English

如何将PHP HTTP_USER_AGENT保存到MySQL字段

[英]How to save PHP HTTP_USER_AGENT to MySQL field

I have a simple feedback form PHP script that I would like to enhance by adding the $_SERVER[HTTP_USER_AGENT] data to the row in the database that I'm saving. 我有一个简单的反馈表单PHP脚本,我想通过将$ _SERVER [HTTP_USER_AGENT]数据添加到我正在保存的数据库中的行来增强。

I keep getting parse errors when I try a simple insert, passing '$_SERVER[HTTP_USER_AGENT]' as a typical string. 当我尝试一个简单的插入时,我继续得到解析错误,将'$ _SERVER [HTTP_USER_AGENT]'作为典型的字符串传递。 Should I bundle it in some way, so that the characters used in that Server variable are not triggering such errors? 我应该以某种方式捆绑它,以便该Server变量中使用的字符不会触发此类错误吗?

(The INSERT query runs fine without that field, btw.) (INSERT查询在没有该字段的情况下运行正常,顺便说一下。)

Thanks. 谢谢。

My bet is that there is a ' in the user agent strings that are causing the parser error. 我敢打赌,用户代理字符串中有一个'导致解析器错误。

The User-Agent string returned to PHP is under control of the local browser, which means that you need to treat it no differently from regular user input. 返回到PHP的User-Agent字符串受本地浏览器的控制,这意味着您需要将其与常规用户输入区别对待。 A malicious user or a user who has been infected by a virus/trojan/worm could change the user agent string to cause an SQL injection attack. 恶意用户或已被病毒/木马/蠕虫感染的用户可能会更改用户代理字符串以导致SQL注入攻击。 At the very least, you need to escape it (with mysql_real_escape_string() for example. My bet is that once you do this, your parser errors should also go away. Better yet, try to move to using prepared statements if your system allows this. 至少,你需要转义它(例如使用mysql_real_escape_string() 。我的赌注是,一旦你这样做,你的解析器错误也应该消失。更好的是,如果你的系统允许这样 ,试着转向使用预准备语句

Does 是否

mysql_query("
INSERT INTO
    db_table
VALUES (
    ...
    '" . mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) . "'
    ...
)");

not work? 不行? Can you show us your whole query? 你能告诉我们你的整个查询吗? What are the exact error-messages? 什么是确切的错误消息?

Without an actual error message it's hard to say what particular problem you encounter with. 如果没有实际的错误消息,很难说您遇到的具体问题。
But to solve all possible issues, 但要解决所有可能的问题,

  • First of all, you must read an official manual page to make yourself understand PHP strings syntax: http://php.net/types.string 首先,您必须阅读官方手册页,以使自己了解PHP字符串语法: http//php.net/types.string

  • Then, you have to understand Mysql proper syntax. 然后,你必须了解Mysql正确的语法。 I've explained it already here 我已经在这里解释过了

  • Finally, you have to put everything together 最后,你必须把所有东西放在一起

like this: 像这样:

$agent = mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']);
$sql   = "INSERT INTO `table` set useragent = '$agent'";
$res   = mysql_query($sql) or trigger_error(mysql_query.$sql);

Running your queries this way you'll never have any problem. 以这种方式运行查询,您将永远不会有任何问题。 Or comprehensive error message at least. 或者至少是全面的错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM