| « Displaying Chinese UTF-8 characters in gvim on Windows | Prosper's insecure bank account management feature » |
$_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:
It seems odd that PHP would refer to something likeThe filename of the currently executing script, relative to the document root.
/foo.php/"><script>alert('hello');</script>as a "filename." - It's pretty bizarre default behavior that PHP will execute
/foo.phpfor a request of/foo.php/bar/baz.
Comments
kavosSuirm on Thursday, October 1, 2026 at 03:51
Пруд на собственной территории — это гордость владельца и уютный уголок природы. Мастера ProfPrud создают пруды любого масштаба и конфигурации под ключ. Ищете <a href=https://tvoyprud.ru/>купить пруд Mосква</a>? На сайте profprud.ru представлены готовые проекты и примеры выполненных работ. Специалисты подберут оборудование, высадят растения и обеспечат сервисное обслуживание. Итогом работы становится красивый пруд с прозрачной водой и надёжной гарантией.
fopelickwoulp on Thursday, October 1, 2026 at 04:16
Профиль продавца на Копейке.шоп — находка для любителей активного отдыха: здесь представлен внушительный ассортимент квадроциклов с доставкой по всей России и удобной оплатой после получения. В каталоге — модели Loncin, Zongshen, Mikilon и другие по ценам от 150 000 до 425 000 рублей. Загляните на <a href=https://kopeika.shop/users/156117>https://kopeika.shop/users/156117</a>, чтобы выбрать надёжную технику для бездорожья и оценить предложения продавца из Хабаровска.
wicosinfuero on Thursday, October 1, 2026 at 06:48
Для эффективной аналитики и масштабирования интернет-бизнеса требуются актуальные данные. Профильный ресурс <a href=https://richman888.keys.shop/>https://richman888.keys.shop/</a> предоставляет свежие базы доменов и структурированные реестры сайтов по CMS. Ежемесячные обновления, полный охват мировых зон и моментальная выдача сведений обеспечивают маркетологам точность и явное преимущество.
mayhisog on Thursday, October 1, 2026 at 08:26
Гидроманипулятор на самосвале расширяет возможности грузовика, позволяя грузить, разгружать и переносить массивные материалы. Компания Steelmagic производит надёжное оборудование под ваши задачи — оформить заказ можно на сайте <a href=https://steelmagic.ru/gidromanipulyator-dlya-samosvala/>https://steelmagic.ru/gidromanipulyator-dlya-samosvala/</a> Качественная сборка, точное управление и долгий срок службы гарантированы.
Kevinhow on Thursday, October 1, 2026 at 10:57
This article might save you time by putting everything in one place <a href=https://mag01.ru/2020/04/19/%d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d1%82-%d0%bc%d0%b8%d1%80/?unapproved=1043193&moderation-hash=92e313410a54c34a435a5704f0ac4ae6#comment-1043193>https://mag01.ru/2020/04/19/%d0%bf%d1%80%d0%b8%d0%b2%d0%b5%d1%82-%d0%bc%d0%b8%d1%80/?unapproved=1043193&moderation-hash=92e313410a54c34a435a5704f0ac4ae6#comment-1043193</a>
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.