简体   繁体   中英

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.

I keep getting parse errors when I try a simple insert, passing '$_SERVER[HTTP_USER_AGENT]' 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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