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

ThomasTam on Friday, March 13, 2026 at 03:17

Experience the latest version here : www.medtronik.ru/

bigirahix on Friday, March 13, 2026 at 03:49

Фирма МВПОЛ занимается монтажом индустриальных напольных систем — полимерных наливных полов, бетонных оснований с топпинг-упрочнением и восстановлением действующих покрытий. Фирма использует профессиональное оборудование и сертифицированные материалы для создания износостойких покрытий на складах, производственных цехах и коммерческих объектах. Ищете <a href=http://mvpol.ru/>реконструкции полов</a>? Подробную информацию о технологиях, стоимости работ и портфолио реализованных проектов можно найти на mvpol.ru где также доступен онлайн-заказ расчета сметы. Предприятие обеспечивает гарантийное обслуживание работ минимум два года и реализует проекты любого масштаба в столичном регионе.

JeffreySer on Friday, March 13, 2026 at 04:46

Recommend taking a couple minutes to read <a href=https://www.postadsnow.in/author/katlynhairston/>https://www.postadsnow.in/author/katlynhairston/</a>

MichealZig on Friday, March 13, 2026 at 09:36

Just found this great piece, thought you might like it <a href=</a>http://51.15.222.43/willismanley17/willis2003/issues/1>http://51.15.222.43/willismanley17/willis2003/issues/1</a>

bezibGah on Friday, March 13, 2026 at 13:42

Сертифицированный партнер поставляет окна Melke и алюминий Alurix с экспертным монтажом по Москве и Московской области. Каталог включает профили Centum, Wide, Evolution, Smart Ultra, Lite70 и Lite60, плюс варианты теплого и холодного балконного остекления. Актуальные цены и полный каталог на <a href=https://xn-----6kccxab8adjjjjc4k.xn--p1ai/>https://xn-----6kccxab8adjjjjc4k.xn--p1ai/</a> — компания обеспечивает бесплатный замер, консультацию специалистов и быструю установку с гарантией качества. Личностно-ориентированная работа с заказчиками обеспечивает воплощение замыслов любого уровня — от классических оконных блоков до фахверка и панорамных порталов.

Add a comment

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

Comment: