tags:

views:

170

answers:

2

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.

+3  A: 

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)

erenon
+3  A: 

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)
Adam Backstrom