PHP_SELF and XSS

McRonald picture McRonald · May 21, 2011 · Viewed 21.5k times · Source

I've found an article claiming that $_SERVER['PHP_SELF'] is vulnerable to XSS.

I'm not sure if I have understood it correctly, but I'm almost sure that it's wrong.

How can this be vulnerable to XSS attacks!?

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <!-- form contents -->
</form>

Answer

John Conde picture John Conde · May 21, 2011

To make it safe to use you need to use htmlspecialchars().

<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>

See A XSS Vulnerability in Almost Every PHP Form I’ve Ever Written for how $_SERVER["PHP_SELF"] can be attacked.