| « 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
Clarksailt on Tuesday, February 24, 2026 at 11:20
Pin Up Casino is one of the most popular online top <a href="https://global-smm.ru/">пинап зеркало</a>
Clarksailt on Tuesday, February 24, 2026 at 11:27
Pin Up Casino is one of the most popular online top <a href="https://global-smm.ru/">https://global-smm.ru/</a>
kumytrdTow on Tuesday, February 24, 2026 at 16:02
Офисная мебель — это не просто столы и стулья, это основа продуктивной работы и комфорта сотрудников. Группа компаний «СОЮЗ» с 2008 года специализируется на комплексном оснащении офисов в Москве, предлагая как стандартные решения, так и мебель на заказ. Посетите <a href=https://group-soyuz.ru/>https://group-soyuz.ru/</a> и убедитесь: здесь создают интерьеры, которые впечатляют партнёров и мотивируют команду. Компания реализует проекты точно в срок и в рамках бюджета, работая с офисами, отелями и учебными заведениями.
qojalyjex on Tuesday, February 24, 2026 at 20:15
Онлайн-кинотеатр предлагает обширную коллекцию фильмов и сериалов различных жанров в высоком качестве. Пользователи получают доступ к новинкам кино, классическим картинам и эксклюзивным премьерам без рекламных пауз. На платформе <a href=https://bestkino.space/>https://bestkino.space/</a> удобная навигация позволяет быстро найти интересующий контент по жанрам, годам выпуска и рейтингам. Регулярное обновление библиотеки гарантирует свежий контент для всех любителей качественного кинематографа. Простая регистрация и интуитивный интерфейс делают просмотр максимально комфортным на любых устройствах.
jokodrok on Tuesday, February 24, 2026 at 23:22
Ремонт квартир в Волгограде под ключ – это комплексный подход от строительной компании Дока строй, где каждая деталь продумана до мелочей Опытные бригады осуществляют отделку добросовестно и в оговоренные сроки, задействуя инновационные технологии и материалы <a href=https://doka-stroi.ru/>https://doka-stroi.ru/</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.