开发者

How to save PHP HTTP_USER_AGENT to MySQL field

开发者 https://www.devze.com 2023-01-06 12:06 出处:网络
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.

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.

I keep getting parse errors when I try a simple insert, passing '$_SERVER[HTTP_USER_AGE开发者_Python百科NT]' as a typical string. Should I bundle it in some way, so that the characters used in that Server variable are not triggering such errors?

(The INSERT query runs fine without that field, btw.)

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. 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. 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.


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

  • Then, you have to understand Mysql proper syntax. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消