Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 838
Yaaqov Avatar asked Jul 05 '10 06:07

Yaaqov


2 Answers

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.

like image 165
Andrew Avatar answered Nov 18 '22 19:11

Andrew


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?

like image 27
Fidi Avatar answered Nov 18 '22 20:11

Fidi