I've seen a lot of warnings about using $_SERVER['REQUEST_URI'] because it can open things up to XSS, but I haven't been able to find anything confirming a safe way to use it. Some people have mentioned using esc_url(), but I wasn't able to find anything confirming how to safely use it. This is my best guess, would this safely prevent XSS attacks?

echo esc_url(( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

If I want to use the URL internally rather than display it, it seems I have to use esc_url_raw(). Is this safe as well?

$pageurl = esc_url_raw(( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

  • 1
    What are you using it for? Printing out in HTML or redirecting the user? – TheDeadMedic May 24 '14 at 15:18
  • I'm using it to build another URL to share the current page on other sites such as twitter. So the final URL is being used in an href. – Josiah Sprague May 24 '14 at 15:27
  • If you think things through, you should rarely even need to consider most $_SERVER values. If you can be more explicit about what you need to accomplish you will get more relevant answers. – s_ha_dum May 24 '14 at 15:32
  • @s_ha_dum That doesn't really help answer the question. I have thought things through, and in this case, I do need to access the $_SERVER variables. The question is how to do so safely. – Josiah Sprague May 24 '14 at 15:36
  • esc_attr should be sufficient – TheDeadMedic May 24 '14 at 15:53

If you are printing the URL out, say to the front end... that is, it is to be displayed as a normal URL to a visitor etc. then:


If you are going to use the URL in, say, a WordPress redirect (or anything else that sends http header 'location', then you will need:


This is actually the basis and fix of this recent security vulnerability: https://blog.sucuri.net/2015/04/security-advisory-xss-vulnerability-affecting-multiple-wordpress-plugins.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.