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


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.

RobinDig on Tuesday, July 21, 2026 at 11:47

Sail through our crisp casino game bay <a href="https://handreporting.com/ink/">bet andreas az</a>

RobinDig on Tuesday, July 21, 2026 at 11:54

Sail through our crisp casino game bay <a href="https://betandreas-br12.com/ink/">https://betandreas-br12.com/ink/</a>

RobinDig on Tuesday, July 21, 2026 at 12:37

Chew on our meaty casino game platter <a href="https://viks-uz3.servicesstarweb.com/">https://viks-uz3.servicesstarweb.com/</a>

RobinDig on Tuesday, July 21, 2026 at 12:40

Chew on our meaty casino game platter <a href="https://uz.viksitbharatambassador.com/">https://uz.viksitbharatambassador.com/</a>

RobinDig on Tuesday, July 21, 2026 at 12:47

Chew on our meaty casino game platter <a href="https://viks-uz3.servicesstarweb.com/">viks</a>

RobinDig on Tuesday, July 21, 2026 at 13:24

Chew on our meaty casino game platter <a href="https://viks.ssregulatoryservices.com/">https://viks.ssregulatoryservices.com/</a>

RobinDig on Tuesday, July 21, 2026 at 13:31

Chew on our meaty casino game platter <a href="https://viks.ssregulatoryservices.com/">https://viks.ssregulatoryservices.com/</a>

RobinDig on Tuesday, July 21, 2026 at 15:13

Wade into our thick casino game jungle <a href="https://slotv1.ru">https://slotv1.ru</a>

RobinDig on Tuesday, July 21, 2026 at 15:16

Wade into our thick casino game jungle <a href="https://slotv1.ru">майнкрафт слоты казино</a>

RobinDig on Tuesday, July 21, 2026 at 15:23

Wade into our thick casino game jungle <a href="https://flintclub.ru">https://flintclub.ru</a>

RobinDig on Tuesday, July 21, 2026 at 15:58

Wade into our thick casino game jungle <a href="https://slotv1.ru">https://slotv1.ru</a>

RobinDig on Tuesday, July 21, 2026 at 16:04

Wade into our thick casino game jungle <a href="https://slotv1.ru">как называется казино про майнкрафт</a>

rizesoKeego on Tuesday, July 21, 2026 at 17:10

Скрытые двери — элегантное решение для современного интерьера: они сливаются со стеной, создавая эффект цельного пространства. Компания предлагает широкий ассортимент — под покраску, в шпоне, с AL-кромкой, по RAL, с зеркалом и стеклянные модели. Ищете <a href=https://www.skrytyedveri.ru/>двери под покраску</a>? На www.skrytyedveri.ru представлен полный каталог скрытых и раздвижных дверей с системами пеналов и фурнитурой. Рейтинг магазина 4.7 — подтверждение высокого качества продукции и сервиса.

nasiruyNep on Tuesday, July 21, 2026 at 18:24

Велакаст — современный индийский дженерик для борьбы с хроническим гепатитом С, содержащий софосбувир и велпатасвир в клинически подтвержденных дозировках. Препарат демонстрирует высокую эффективность при лечении различных генотипов вируса, обеспечивая выздоровление у большинства пациентов за стандартный курс терапии. На информационном портале <a href=https://velakast.org/>https://velakast.org/</a> представлены подробные инструкции по правильному заказу оригинального препарата, методы проверки подлинности и защиты от подделок, а также экспертные материалы о гепатите С с отзывами пациентов и ответами на актуальные вопросы для безопасного и результативного лечения.

repuwvon on Tuesday, July 21, 2026 at 20:50

Glassway Group производит стеклянные конструкции любой сложности: перегородки, душевые ограждения, двери и перила. Вся продукция изготавливается из закалённого стекла и комплектуется прочной фурнитурой. Ищете <a href=https://glassway.group/>офисные перегородки</a>? Каталог и примеры работ смотрите на сайте glassway.group — там же можно оформить заявку. Собственная команда компании проводит замер, привозит и монтирует изделия без задержек.

Add a comment

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

Comment: