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


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.

tegedewtucky on Friday, February 13, 2026 at 01:17

Офисная мебель — это не просто столы и стулья, это основа продуктивной работы и комфорта сотрудников. Группа компаний «СОЮЗ» с 2008 года специализируется на комплексном оснащении офисов в Москве, предлагая как стандартные решения, так и мебель на заказ. Посетите <a href=https://group-soyuz.ru/>https://group-soyuz.ru/</a> и убедитесь: здесь создают интерьеры, которые впечатляют партнёров и мотивируют команду. Компания реализует проекты точно в срок и в рамках бюджета, работая с офисами, отелями и учебными заведениями.

culurimpog on Friday, February 13, 2026 at 04:13

Hellion делает ставку на практичную электронику для автозвука: процессорные решения, усиление, акустика, сабвуферы, мультимедиа и кабельная обвязка, дополняемые сервисом и программным обеспечением. Ищете <a href=https://hellion-rus.ru>лучшие автомобильные усилители звука</a>? На hellion-rus.ru — 3 года гарантии при покупке на сайте, оплата картами и обещание доставки по Москве за 6 часов при заказе до 12:00; есть отзывы, что помогает выбрать комплект без лишних рисков. Покупателю обещают 3 летнюю гарантию при заказе на сайте, оплату картами и быструю доставку по Москве при заказе до 12:00, а FAQ, блог и отзывы упрощают подбор оборудования.

Ralphwaf on Friday, February 13, 2026 at 06:42

Highly recommend giving this a read if you want a better grasp of the subject <a href=https://vacantes.pepmendoza.com.ar/companies/archive-diploms-24/>https://vacantes.pepmendoza.com.ar/companies/archive-diploms-24/</a>

bomugCam on Friday, February 13, 2026 at 07:55

Cercate <a href=https://www.teatroverga.it/it-it/>casino mania</a>? Accedi a teatroverga.it/it-it/ e scoprirai più di 6.000 giochi per ogni preferenza, con bonus casinò istantanei che assicureranno un'esperienza di gioco straordinaria! Scopri di più su depositi e prelievi, registrazione del conto e tutti i vantaggi della nostra app mobile. Hai anche la possibilità di vedere tutti i bonus accessibili qui. CasinoMania è un casinò regolarmente autorizzato con licenza ufficiale.

Add a comment

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

Comment: