| « 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
burumGrili on Wednesday, October 7, 2026 at 14:59
Засор в трубе парализует быт мгновенно. Мастера по прочистке стоков в Москве закрывают вопрос без повторных приездов. Работа идёт до чистых стенок: гидродинамика вымывает наросты полностью. Ищете <a href=https://prochistka-msk.ru/>для чистки канализации</a>? Оформить заявку можно на сайте prochistka-msk.ru — оператор перезвонит и согласует удобное время. Проблема уходит основательно, а не откладывается на неделю.
risumidPog on Wednesday, October 7, 2026 at 16:00
Сайт <a href=https://xn--42-6kcajlib1a3cg0ahhp3l4c.xn--p1ai/>https://xn--42-6kcajlib1a3cg0ahhp3l4c.xn--p1ai/</a> посвящён садовым растениям и декоративным культурам для оформления участка. В каталоге представлены гортензии, декоративные кустарники и многолетние растения, которые подходят для создания красивых цветников, композиций и уютных садовых уголков. Здесь можно познакомиться с разнообразием растений, их особенностями и вариантами использования в ландшафтном оформлении. Сайт будет полезен садоводам, дачникам и всем, кто интересуется выращиванием и озеленением участка.
wayiduickFen on Wednesday, October 7, 2026 at 17:17
Покупка машины больше не требует сложных согласований: сервис <a href=https://cartrip-auto.ru/>https://cartrip-auto.ru/</a> предлагает прозрачную аренду автомобилей с быстрым правом выкупа в Краснодарском крае без скрытых условий и волокиты. Клиентам открыт огромный проверенный автопарк под любые задачи с гибким графиком платежей на срок до сорока месяцев. Это надежный, комфортный и проверенный путь к собственной машине уже сегодня.
depizfaf on Wednesday, October 7, 2026 at 17:58
Aigena — российская студия ИИ-генерации фото, видео и музыки без VPN и зарубежных карт. FLUX, Kling, Veo и Suno собраны на одной площадке и работают на едином счёте. Ищете <a href=https://aigena.pro/>нейросеть для создания видео</a>? Просто зайдите на aigena.pro и опишите задачу на русском. Оплата в рублях картой РФ или через СБП, неудачные генерации возвращаются на счёт. Готовый файл вы получаете уже через несколько минут.
mexavyGah on Wednesday, October 7, 2026 at 18:34
Navigating the vast expanse of the Americas requires reliable precision, and <a href=https://us-atlas.com/>https://us-atlas.com/</a> delivers exactly that through an exhaustive digital atlas. From intricate highway networks and county lines across all fifty U.S. states to national parks, Canada, and Latin America, this rich resource turns complex geography into clear visual knowledge.
pabebHex on Wednesday, October 7, 2026 at 18:42
Looking for <a href=https://ergauge.com/>ergauge - anonymous instagram story viewer</a>? Head over to ergauge.com—the service is completely free, and your visit will never appear in view counts or story audience statistics. You can also unlock hidden profile analytics that the platform normally tracks—including engagement rate, average likes, posting frequency, and individual post performance—all in real-time and based on public data.
racetStoda on Wednesday, October 7, 2026 at 18:57
Савина Ирина консультирует взрослых клиентов онлайн уже более трёх лет. Темы работы: тревожность, ощущение пустоты, одни и те же сценарии в отношениях, горе, потеря смысла жизни. Ищете <a href=https://xn--90aefa6bo.shop/психолог-онлайн/>психологическая помощь</a>? Подробное портфолио и описание подхода собраны на оберег.shop/психолог-онлайн/ — там же видно, как проходят сессии. Индивидуальный формат даёт устойчивость и прикладные приёмы для повседневной жизни. Стартовая точка — выяснить, комфортно ли вам работать именно со мной.
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.