| « 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
bocardaw on Thursday, November 5, 2026 at 17:48
За 15 лет работы «Идеал Строй» построила в Москве и области десятки домов и коттеджей под ключ. В ходу газобетон, газоблок и кирпич, фундаменты всех видов, фасадные работы, дренаж и благоустройство территории. Проект, смета и сроки прописываются в договоре. Подробные цены и каталог готовых проектов опубликованы на сайте <a href=https://idealstr.ru/>https://idealstr.ru/</a> — там же примеры сданных объектов. Своя техника у бригад и прямые закупки материалов на заводах.
rupebythich on Friday, November 6, 2026 at 01:22
Современная игровая платформа Wilder привлекает внимание аудитории внушительной коллекцией из девяти тысяч лицензионных слотов от ведущих провайдеров индустрии. На официальном портале <a href=https://wilder.black/ThZhzqSvu>https://wilder.black/ThZhzqSvu</a> участников ждут динамичные турниры, прозрачная программа лояльности и оперативный вывод средств. Грамотный сервис создает комфортные условия для честного отдыха.
sicilyelDuemn on Friday, November 6, 2026 at 02:47
Возвращение безупречной свежести и мягкости домашнему текстилю требует тонкого фабричного подхода. Тульская специализированная химчистка <a href=https://xn--b1agkeimcs.xn--p1ai/>https://xn--b1agkeimcs.xn--p1ai/</a> проводит профессиональное глубокое обеспыливание, бережную стирку гипоаллергенными средствами, дезинфекцию и сушку ковров с комфортным бесплатным вывозом и доставкой прямо к вашему порогу.
yofavlicore on Friday, November 6, 2026 at 04:01
Грамотное обслуживание современного автомобиля требует бескомпромиссного качества деталей и профессионального подхода к их поиску. Специализированный онлайн-магазин <a href=https://mobizap.ru/>https://mobizap.ru/</a> предоставляет автовладельцам обширный каталог оригинальных запчастей, надежных аналогов, моторных масел и расходников. Удобная система подбора по VIN-коду, выгодные цены и оперативная доставка гарантируют уверенность в каждой поездке.
vodudrJag on Friday, November 6, 2026 at 11:21
Компания Полиметалл производит гидравлические прессы с усилием от 1 до 200 тонн под техническое задание заказчика. Каталог включает ручные и электрогидравлические прессы с плитами различных габаритов. Выбрать оборудование можно на сайте <a href=https://tecamet.ru/pressy/pressy-gidravlicheskie>https://tecamet.ru/pressy/pressy-gidravlicheskie</a> без переплаты посредникам. Технику берут автосервисы, кузницы, пищевые и мебельные производства для выпрессовки, гибки, отжима и склейки. К каждому прессу прилагаются паспорт и инструкция по эксплуатации.
tojunsaF on Saturday, November 7, 2026 at 02:55
Специалисты по кибербезопасности помогают защищать аккаунты, проводить разрешённые проверки и возвращать доступ к собственным данным. Подробная информация о консультациях и легальном аудите размещена на <a href=https://xakerplus.com/threads/predlozhenie-uslug-xakera-vzlom-pochty-socialnyx-setej-i-drugie-xakerskie-uslugi-perechen-uslug-gorazdo-bolshe-pishite.13025/>https://xakerplus.com/threads/predlozhenie-uslug-xakera-vzlom-pochty-socialnyx-setej-i-drugie-xakerskie-uslugi-perechen-uslug-gorazdo-bolshe-pishite.13025/</a> Специалисты работают только по согласованному заданию и в правовом поле.
Jamesinacy on Saturday, November 7, 2026 at 03:08
welacsjAr on Saturday, November 7, 2026 at 07:38
В SMS PRO можно купить виртуальный номер для приёма SMS или готовый аккаунт Telegram. Платформа работает с более чем 600 сервисами и 180 странами, номер приходит сразу после оплаты. Заказать номер можно на сайте <a href=https://sms-pro.app/>https://sms-pro.app/</a> за пару минут без лишних шагов. Если код не пришёл в отведённое время, деньги автоматически возвращаются на баланс. За три года сервис собрал свыше 1400 отзывов и дополнил Telegram-бот полноценным сайтом.
bosumHoift on Saturday, November 7, 2026 at 08:25
The electronic atlas of America contains detailed maps of the USA, Canada, Mexico, and the nations of South America. The collection features political, road, and topographic maps of states, national parks, and cities. All materials are available on the website <a href=https://us-atlas.com/>https://us-atlas.com/</a> for free and in a convenient format. Each map can be explored online or printed out for travel, work, and study.
BrianCes on Sunday, November 8, 2026 at 02:06
https://intercom.help/best-betting/en/articles/17827780-code-promo-1xbet-togo-2026-1x200era-credit-absent
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.