Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitize $_SERVER['HTTP_USER_AGENT'] & $_SERVER['HTTP_REFERER'] before saving to DB?

I have a feedback form which will take a couple of user inputted fields along with a few fields generated by PHP functions like 'user-agent' and 'referer.'

My question is should these strings be sanitized before being inputted? I realize one could easily alter the user-agent and the referring page, but could it be possible for a visitor to add a SQL injection like string so when PHP pulls this info it potentially breaks my form?

For instance if a user changed their user-agent or referring page to include the string Robert'); DROP TABLE Students;--

like image 398
Eric Avatar asked Oct 21 '25 10:10

Eric


2 Answers

The word "sanitize" is pretty ambiguous and and better to be avoided.

Speaking of a database interaction, there is no need to "sanitize" at all. Just use prepared statements.

What is even more important, the data source doesn't matter. It should never be a question, "should we properly handle the data from such and such source?". It's just illogical, if you think of it. Why making such a distinction? Why rely on such a vague judgement? Why not to have an established process that uniformly treats any data despite the source?

Not to mention it's just super simple to use prepared statements:

$stmt = $db->prepare("INSERT INTO log (user_agent, referrer) VALUES (?,?)");
$stmt->execute([$_SERVER['HTTP_USER_AGENT'],$_SERVER['HTTP_REFERER']]);

And it will not only make the code simpler yet secure, but also make it proof against human errors of all sorts.

like image 194
Your Common Sense Avatar answered Oct 22 '25 23:10

Your Common Sense


Simple Answer: validate/sanitize/escape everything (like client-side data, for example) because everything could be modified and evil or contain unexpected characters that could break your query (like Col. Shrapnel explained).

to minimize risk you should also about using prepared statements instead of building SQL-strings on your own (Note: this doesn't mean you can leave out the checks).

like image 23
oezi Avatar answered Oct 22 '25 23:10

oezi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!