$_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 (6)


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.

gurowrAtort on Monday, November 2, 2026 at 17:29

Специализированный магазин VIDEO-CAMER поставляет передовое сертифицированное оборудование для надежной комплексной безопасности объектов. На удобном сайте <a href=https://video-camer.ru/>https://video-camer.ru/</a> собраны современные IP-камеры, видеорегистраторы, детекторы и поисковые приборы от ведущих брендов. Круглосуточный график работы, оперативная доставка по России и экспертная помощь делают сервис безупречным.

nuyuziePaync on Tuesday, November 3, 2026 at 04:52

Lucky Jet — краш-игра, где честность каждого раунда можно проверить, а итог виден за секунды. Промокод R249V и условия стартового пакета размещены на <a href=https://selectorggbrillx.wixsite.com/website>https://selectorggbrillx.wixsite.com/website</a> в открытом доступе. Стартовый пакет 1win включает до 600% к первым пополнениям, 500 бесплатных вращений и кэшбэк до 40% каждую неделю. Покерные фрироллы с гарантией 1000$ проводятся с периодичностью раз в два дня.

cirooennum on Tuesday, November 3, 2026 at 13:47

ГК «ПСК» в Тюмени производит железобетонные изделия для дорожного, гражданского и железнодорожного строительства. Предприятие выпускает более 1000 видов изделий, включая плиты перекрытия, сваи, лотки, бордюры, брусчатку и утяжелители. Полный каталог с ценами размещен на сайте <a href=https://gk-psk72.ru/>https://gk-psk72.ru/</a> в открытом доступе. Большинство изделий всегда в наличии и отпускается в день оформления заказа. Компания доставляет ЖБИ в Тюменскую область, ХМАО и ЯНАО и предоставляет сертификаты на каждый вид изделий.

xexuksrox on Tuesday, November 3, 2026 at 14:47

Интернет-магазин Резиденция детства объединил больше миллиона товаров для детей и родителей в одном месте. Тут вас ждут игрушки, настольные игры, товары для дома, отдыха и развития ребёнка по выгодным ценам. Весь ассортимент доступен на <a href=https://childresidence.ru/>https://childresidence.ru/</a> без лишних переплат. Регулярные акции делают покупки ещё выгоднее, а быстрая доставка радует всю семью.

tutiwardGib on Tuesday, November 3, 2026 at 21:43

Освоить востребованную и престижную профессию в индустрии красоты с нуля приглашает московская школа парикмахеров Юлии Бурдинцевой. Учебный процесс построен на интенсивной практике с живыми моделями, а на странице <a href=https://j-center.ru/>https://j-center.ru/</a> представлены программы от базовых техник до сложной колористики с официальным дипломом и содействием в трудоустройстве.

Add a comment

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

Comment: