$_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.

vozizimet on Monday, April 13, 2026 at 01:29

«Ветреный» — турецкая драма 2019 года о двух людях, оказавшихся в плену многолетней семейной вражды. Миран появляется в Мидьяте с единственной целью — взять в жёны Рейян и тем самым сломить враждебный род. Ищете <a href=https://vetrenyy-smotret.biz/>ветреный смотреть онлайн</a>? Все 256 серий доступны бесплатно на vetrenyy-smotret.biz с русской озвучкой в хорошем качестве. Однако расчёт даёт трещину — искренняя и непреклонная Рейян вызывает в нём то, с чем он не умеет справляться. Захватывающие виды, острые диалоги и мощная игра актёров ставят сериал в ряд лучших турецких драм.

xidaxiMed on Monday, April 13, 2026 at 02:08

«Магическая битва» — беспощадное и интеллектуальное аниме о мире, в котором людские страхи и страдания принимают облик смертоносных проклятий. Школьник Юдзи Итадори случайно проглатывает палец древнего демона и превращается в его носителя — теперь в одном теле сосуществуют обычный парень и чудовище, которого боятся опытные маги. Ищете <a href=https://magicheskaya-bitva.biz/>магическая битва все серии</a>? На magicheskaya-bitva.biz все 58 серий трёх сезонов доступны бесплатно в отличном качестве с профессиональной озвучкой. Захватывающие битвы, многогранные характеры и пронизывающая мрачность повествования ставят сериал в число лучших аниме последних лет.

vesijordziste on Monday, April 13, 2026 at 02:37

Здоровье животных начинается с правильного питания, и здесь на помощь приходит гранулированная люцерна торговой марки «Люцервик» — натуральная витаминно-минеральная мука, сохраняющая до 95% полезных веществ исходного сырья. Продукт идеально подходит для лошадей, крупного рогатого скота, птицы и кроликов, обеспечивая животных качественным белковым кормом без химических добавок. На <a href=https://xn--b1afkib5a3byd.xn--p1ai/>https://xn--b1afkib5a3byd.xn--p1ai/</a> можно оформить заказ оптом и в розницу с доставкой из Кирова, изучить каталог, фотогалерею и реальные отзывы покупателей. Гранулы удобно хранятся и легко дозируются, что делает их незаменимым решением для фермеров и частных хозяйств.

Add a comment

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

Comment: