I have simple PHP code for checking IP:



echo ("<h1><b>Your IP:</b> $ip<h1>");

If I use htmlentities, then my html doesn't work.

What is the best way to protect it against XSS?

  • 1
    Why can't you use htmlentities() on just the $ip variable, then include that?
    – Matthew
    Commented Jan 19, 2017 at 11:02
  • 5
    Assuming you trust your web server not to return arbitrary strings in the remote address variable there is no need for XSS filtering here. Neither an IPv4 nor IPv6 can be an XSS vector. Commented Jan 19, 2017 at 11:05
  • 1
    I forgot to mention that HTTP_USER_AGENT is used in code: $browser=$_SERVER['HTTP_USER_AGENT']; echo ("<h5><b>Your user agent:</b> $browser<h5>");, would this make a code still vuln. to xss?
    – user134969
    Commented Jan 19, 2017 at 12:45
  • 2
    @user134969 user-agent is up to the user and can be absolutely anything (as opposed to an IP which follows a specific format) so it's vulnerable. However given that it's triggered by a header I'm not sure how this can affect anyone but the attacker himself, as you have to explicitly send a malicious header to be XSS'ed and you can't embed headers in an URL or similar to trick a third party. Commented Jan 19, 2017 at 13:48
  • 2
    Right, it would have to be "Here are the last 5 user agents that accessed our service: _______" which would store those UAs temporarily, that would allow the user agent to be an XSS vector for someone other than the user of the page.
    – CR Drost
    Commented Jan 19, 2017 at 16:19

1 Answer 1


Use htmlentities just on the user-supplied data:

$escaped_ip = htmlentities($ip);
echo ("<h1><b>Your IP:</b> $escaped_ip<h1>");

If you are writing a real application, it would be better to use some template language that escapes values by default. This makes it easier for the developer to do it correctly, making it more secure.

  • how can one make $ip != $escaped_ip? and if we can't, what's the point?
    – dandavis
    Commented Jan 19, 2017 at 18:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .