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


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.

purudowRum on Tuesday, May 5, 2026 at 03:45

Ищете где посмотреть сериал Во все тяжкие онлайн? Посетите сайт <a href=https://xn-----dlcbpbgqr8a9ao3o.org/>https://xn-----dlcbpbgqr8a9ao3o.org/</a> - там вы сможете найти все серии всех сезонов. Просмотр онлайн без регистрации и в отличном качестве. Если вы еще не смотрели легендарный сериал - самое время! А если вы являетесь фанатом, то на сайте для вас представлены все самые свежие новости о сериале.

xosaxdaubs on Tuesday, May 5, 2026 at 06:42

«РазВикТрейд» — производитель из Беларуси, ориентированный на изготовление пресс-форм и пластиковых изделий для клиентов двух стран. Производство охватывает полный цикл — начиная с технической документации и заканчивая готовой продукцией на складе заказчика. Ищете <a href=https://press-forma.by/>пластика изделия</a>? На press-forma.by можно оставить заявку и получить расчёт проекта. Производственные мощности на 1000 кв.м. с 24 единицами техники позволяют стабильно отгружать более 1,5 млн изделий каждый месяц. Сотрудничество с компанией позволяет сократить затраты и увеличить маржинальность бизнеса в разы.

mipahoFub on Tuesday, May 5, 2026 at 08:17

Анапа — жемчужина черноморского побережья, и исследовать её по-настоящему можно только за рулём собственного, пусть и арендованного, автомобиля. Сервис <a href=https://auto-arenda-anapa.ru/>https://auto-arenda-anapa.ru/</a> предлагает прокат без залога, без ограничения пробега и с неограниченной страховкой ОСАГО, что делает каждую поездку абсолютно беззаботной. Детское кресло и видеорегистратор включены в комплектацию, а оформление занимает три простых шага: выбрать автомобиль, отправить документы и указать место подачи. Команда профессионалов CarTrip всегда на связи в мессенджерах и готова ответить на любой вопрос. Путешествуйте свободно!

Add a comment

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

Comment: