Andromeda
Andromeda

Reputation: 111

how to escape $_SERVER["HTTP_REFERER"] since its a common attack vector for web apps

I'd like to get a referer url with php and read this answer here: https://stackoverflow.com/a/1864617/3405979 and have the following questions: Do you have more information regarding this issue? But more importantly: Do you know how to escape $_SERVER["HTTP_REFERER"]?

Upvotes: 0

Views: 2193

Answers (1)

IMSoP
IMSoP

Reputation: 98015

Escaping is never(*) dependent on the source of the data, only on the destination of the data. That is, if the data has come from anywhere that you do not have complete control over, you need to apply appropriate escaping for the context where you are using the data.

For instance:

  • if outputting in HTML, use htmlspecialchars() or html_entities()
  • if adding as a parameter of another URL, use urlencode()
  • if saving to a DB, use the appropriate quoting function such as mysqli_real_escape_string, pg_escape_string, or PDO::quote; or use a correctly parameterised prepared query which completely separates query from data

These functions are the same no matter what untrusted data you are escaping, e.g.

  • Browser request parameters from $_GET, $_POST or $_COOKIE
  • HTTP headers etc from $_SERVER
  • Data loaded from one context, then passed to another - e.g. data retrieved from your DB and displayed in HTML, since that might originally have come from another untrusted source. Even retrieving from one DB and saving to another still needs proper handling, since what you are returned is the "real" data, not the escaped representation.

If in doubt, escape it. As long as you escape immediately before use/display, you should have no problems with double-escaping.

(*) feel free to point out an exception to this rule...

Upvotes: 10

Related Questions