Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP $_SERVER['HTTP_HOST'] escaping, does this look acceptable?

Tags:

php

escaping

I am just learning about escaping things and started reading about how it could be risky to use $_SERVER['HTTP_HOST'] due to XSS attacks.

I came up with this and was wondering if I could get some feedback on my attempt.

htmlspecialchars(
    filter_var( $_SERVER[ 'HTTP_HOST' ], FILTER_SANITIZE_URL ),
    ENT_QUOTES, 'UTF-8'
)

Does it look okay?

So much depends on this one variable being secure, I just had to ask for input.

EDIT:

I will be using this for display throughout the site, including basic anchor-hrefs, form-actions, etc.

like image 310
Jeff Avatar asked Jan 28 '26 14:01

Jeff


2 Answers

Different escaping functions should be used for different situations, for example:

  • urlencode for items that will be dropped in a query string in an <a> tag, ie. echo '<a href="index.php?foo=' . urlencode($foo) . '">'; (see also http_build_query)
  • mysql_real_escape_string for variables going in a SQL statement (though I prefer bind variable)
  • htmlentities for strings you want to display to the user, that may possibly have HTML within (see also strip_tags)

It depends on what do you want to use for. If you want to display it, use htmlspecialchars. If you want to use as a database query, you might use mysql_real_escape_string in case of mysql. (or prepared statements)

like image 27
erenon Avatar answered Jan 31 '26 03:01

erenon



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!