$_SERVER['PHP_SELF'] and cross-site scripting

Monday, May 20, 2013


It's tempting to assume that PHP's $_SERVER array mostly contains fields out of the reach of an attacker, since these are "server" variables. However, that's not always the case; in particular, the seemingly innocuous PHP_SELF field can be a vector for cross-site scripting.

For example, consider the following foo.php:

<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
    <!-- ...form elements... -->
</form>

If I visit http://www.example.com/foo.php, $_SERVER['PHP_SELF'] will be /foo.php and everything will work correctly.

But what if I visit http://www.example.com/foo.php/"><script>alert('hello');</script> instead? Then the rendered HTML will be:

<form method="POST" action="/foo.php/"><script>alert('hello');</script>">
    <!-- ...form elements... -->
</form>

This allows injection of arbitrary script running under the host site's context, also known as XSS. Two ways to fix this are:

  • Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. The former is the name of the actual script file and can't normally be manipulated by an attacker.
  • Use htmlspecialchars(), which by default will escape double-quotes and prevent a user-supplied string from breaking out of an HTML attribute context.

By the way, this was pretty surprising behavior to me for two reasons:

  • The documentation of PHP_SELF is misleading: The first sentence says:

    The filename of the currently executing script, relative to the document root.

    It seems odd that PHP would refer to something like /foo.php/"><script>alert('hello');</script> as a "filename."
  • It's pretty bizarre default behavior that PHP will execute /foo.php for a request of /foo.php/bar/baz.

Tags: php, xss, security | Posted at 11:13 | Comments (4)


Comments

David Annis on Wednesday, June 25, 2014 at 06:32

I have used the fact that php will execute /foo.php from a request that contains /foo.php/bar to make search engine friendly URLs because many search engines will not index both wheretodrink.php?answer=bar and wheretodrink.php?answer=home because they fear an infinite set of URLs.

tamihelRar on Friday, April 3, 2026 at 01:02

«Сплетница» — американский хит 2007 года о манхэттенской элите, за блестящим фасадом которой бушуют интриги, измены и беспощадная схватка за социальный статус. Возвращение Серены Ван дер Вудсен в Верхний Ист-Сайд мгновенно разрушает шаткое равновесие и ставит под удар трон «королевы школы» Блэр Уолдорф. Ищете <a href=https://spletnitsa-smotret.online/>сплетница все серии</a>? На spletnitsa-smotret.online все 121 серия шести сезонов доступна бесплатно в хорошем качестве. Анонимный блогер Сплетница держит весь Манхэттен в страхе, публикуя разоблачительные материалы о каждом — и никто не знает, кто скрывается за этим ником.

nezohBar on Friday, April 3, 2026 at 02:50

Компания «МСК Строй Групп» работает на московском строительном рынке десять лет и выполняет полный цикл ремонта квартир, офисов, коттеджей и торговых площадей под ключ. Работы выполняют опытные мастера с практикой от семи лет — на все результаты их труда компания предоставляет официальную гарантию сроком от года. Ищете <a href=https://www.msk-stroygroup.ru/>дренаж участка под ключ москва</a>? На msk-stroygroup.ru можно рассчитать стоимость онлайн через калькулятор и заказать выезд специалиста на объект. Компания полностью берёт на себя подбор и доставку материалов с корпоративной скидкой — комплексный заказ экономит клиенту до 20% от общей стоимости проекта.

teteleTaunk on Friday, April 3, 2026 at 03:52

Необходимо благоустройство участка под ключ? Посетите сайт Идеал строй <a href=https://idealstr.ru/uslugi/blagoustrojstvo-territorii>https://idealstr.ru/uslugi/blagoustrojstvo-territorii</a> - ознакомьтесь с нашими работами или звоните по телефону +7 495 227 58 48 - наши квалифицированные сотрудники ответят на все интересующие вас вопросы.

Add a comment

Name:
Email: (optional, not displayed to public)
URL: (do not fill this in — leave blank!)

Comment: