| « 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
RobinDig on Sunday, June 14, 2026 at 13:47
Bruh just peep our unhinged casino games and thank us later <a href="https://igraemveselo.ru">https://igraemveselo.ru</a>
RobinDig on Sunday, June 14, 2026 at 13:53
Bruh just peep our unhinged casino games and thank us later <a href="https://gamelists.ru">https://gamelists.ru</a>
lucaxnyPorce on Sunday, June 14, 2026 at 18:33
Велакаст — современный препарат, заслуживающий внимания тех, кто ответственно подходит к терапии. Пропускать приём нежелательно: это снижает эффективность лечения, а самостоятельно менять дозировку нельзя. Полную инструкцию, данные о совместимости и побочных эффектах вы найдёте на официальном ресурсе по ссылке <a href=https://velakast.pro/>https://velakast.pro/</a> Доверяйте проверенной информации и заботьтесь о здоровье грамотно.
javuknFef on Sunday, June 14, 2026 at 23:37
Шукаєте поради та порівняння товарів? Завітайте на сайт <a href=https://dy.com.ua/>https://dy.com.ua/</a> і ви дізнаєтесь як вибрати обладнання, товари для дому, автомобілі, туризм, спорт та щоденне використання. Ознайомтеся з категоріями на сайті і ви обов'язково знайдете добірки та порівняння на свій смак!
Stevenchile on Monday, June 15, 2026 at 00:02
http://mediatorsamara.ru/language/pages/1xbet_promokod_pri_registracii_bonus.html
RobinDig on Monday, June 15, 2026 at 01:37
On god our casino games are built different come see why <a href="https://vivicasino-apk.com/uz/">https://vivicasino-apk.com/uz/</a>
RobinDig on Monday, June 15, 2026 at 01:46
On god our casino games are built different come see why <a href="https://vivicasino-apk.com/uz/">https://vivicasino-apk.com/uz/</a>
dasifeonsix on Monday, June 15, 2026 at 01:59
Рекламное агентство «Транзит Медиа» специализируется на наружной рекламе в Крыму: брендировании транспорта плёнкой ORACAL, оклейке торговых точек и витрин, изготовлении баннеров и сеток с пропаем и люверсами. Компания располагает собственным производством <a href=https://transitmedia.ru/>https://transitmedia.ru/</a> — лазерная резка, термогибка акрила, ПЭТ и ПВХ. Все работы выполняются как в собственном боксе, так и на территории заказчика по Симферополю, Севастополю и Ялте.
RobinDig on Monday, June 15, 2026 at 02:37
On god our casino games are built different come see why <a href="https://vivicasino-apk.com/uz/">https://vivicasino-apk.com/uz/</a>
RobinDig on Monday, June 15, 2026 at 02:44
On god our casino games are built different come see why <a href="https://vivicasino-apk.com/uz/">vivi registratsiya</a>
diwikoweeni on Monday, June 15, 2026 at 03:57
Три ключевые угрозы современного интернета — реклама, слежка и цензура — AdGuard нейтрализует одновременно. Пользователям доступны VPN с мощным шифрованием, фильтрация рекламы и DNS-защита на любой платформе. Ищете <a href=https://adsguard.ru>адгуардвпн промокод</a>? Подключиться легко — достаточно перейти на adsguard.ru воспользоваться промокодом и сэкономить на подписке. Шифрованный туннель скрывает активность пользователя от интернет-провайдера и рекламных систем. Поддерживаются Windows, Android, iOS и Mac.
RobinDig on Monday, June 15, 2026 at 04:13
Hype up and demolish our ridiculously loaded casino games vault <a href="https://foro.asturmet.com/index.php?topic=62008.0">Vegastars Casino</a>
RobinDig on Monday, June 15, 2026 at 04:22
Hype up and demolish our ridiculously loaded casino games vault <a href="https://martinloon17283.blogripley.com/41325012/unleashing-the-enjoyment-at-vegastars-casino">https://martinloon17283.blogripley.com/41325012/unleashing-the-enjoyment-at-vegastars-casino</a>
RobinDig on Monday, June 15, 2026 at 05:12
Hype up and demolish our ridiculously loaded casino games vault <a href="https://todayspredict.com/blog/2026/03/19/bonus-hunting-in-2026-which-casino-promotions-are-actually-worth-your-time/">Vegastars1</a>
RobinDig on Monday, June 15, 2026 at 05:18
Hype up and demolish our ridiculously loaded casino games vault <a href="https://angeloyced73950.jaiblogs.com/67589809/unleashing-the-pleasure-at-vegastars-casino">https://angeloyced73950.jaiblogs.com/67589809/unleashing-the-pleasure-at-vegastars-casino</a>
kiloseAmick on Monday, June 15, 2026 at 05:23
Looking for <a href=https://foreck.info/>stock market</a>? Foreck.info offers comprehensive coverage of forex, crypto, and stock markets, including thorough analysis and future growth outlooks. In-depth news analysis keeps you informed and current with the latest happenings. The platform showcases leading crypto exchanges, evaluated by experts through eight distinct weighted categories. Discover all the details by visiting the website.
yunuviedaf on Monday, June 15, 2026 at 05:47
Visit the entrepreneurs' blog <a href=https://heavyeyes.net/>https://heavyeyes.net/</a> , where you'll find valuable advice, business plans, lessons, and business ideas for both beginners and experienced entrepreneurs. Learn all about business technologies, innovation, and creativity. This blog will help you stay on top of global trends and always be ahead of the curve.
juvexidBoona on Monday, June 15, 2026 at 06:38
Suchen Sie einen privaten Transfer vom Flughafen Thessaloniki? Besuchen Sie <a href=https://halkidiki-taxi-transfer.gr/>https://halkidiki-taxi-transfer.gr/</a> und buchen Sie Fahrten zum Festpreis mit einem freundlichen, ortskundigen Fahrer – fur eine entspannte Ankunft nach einem langen Flug. Buchen Sie online. Wir erwarten Sie mit einem Schild am Flughafen. Kindersitze sind kostenlos. Weitere Informationen finden Sie auf der Website.
wowuPak on Monday, June 15, 2026 at 08:18
Visit <a href=https://btctoxmr.net/>https://btctoxmr.net/</a> - we help users exchange Bitcoin for Monero through a direct crypto-to-crypto swap flow. Enter the BTC amount, view the estimated XMR payout, and create an exchange order using the form below. The service supports fast Bitcoin to Monero exchange, no registration, and no KYC for standard crypto-to-crypto routes, with final terms and conditions displayed before the transaction begins.
jomedbrush on Monday, June 15, 2026 at 08:34
Арт-студия «Праздничный город» организует свадьбы, выпускные и корпоративы в Санкт-Петербурге и Ленинградской области под ключ: выездная регистрация, декор живыми цветами, драпировка тканью, свадебный кортеж, фото и видеосъёмка, торт, артисты и фейерверк — всё в одном месте. Ищете <a href=https://svadba-812.ru/>организация новогоднего корпоратива</a>? Подробности на svadba-812.ru — полный спектр услуг с готовыми проектами и прозрачными ценами для безупречного праздника. — полный спектр услуг с готовыми проектами и прозрачными ценами для безупречного праздника.
RobinDig on Monday, June 15, 2026 at 12:14
Sheesh our casino games are next level you ain't ready <a href="https://cheat4games.ru">https://cheat4games.ru</a>
RobinDig on Monday, June 15, 2026 at 12:24
Sheesh our casino games are next level you ain't ready <a href="https://bestgame-online.ru">https://bestgame-online.ru</a>
RobinDig on Monday, June 15, 2026 at 13:18
Sheesh our casino games are next level you ain't ready <a href="https://kazinointernet.ru">https://kazinointernet.ru</a>
RobinDig on Monday, June 15, 2026 at 13:25
Sheesh our casino games are next level you ain't ready <a href="https://gameotvety.ru">https://gameotvety.ru</a>
yamedirof on Monday, June 15, 2026 at 16:20
Visit <a href=https://shanghaiatlas.com/>https://shanghaiatlas.com/</a> for a working atlas of Shanghai's landmarks, gardens, towers, and temples. We've compiled only the best—twelve entries on the places visitors actually go to in Shanghai—researched by us on the spot, complete with opening hours, ticket prices, directions, and practical tips. Learn more on the website.
fetefaquife on Monday, June 15, 2026 at 18:56
Looking for a high-quality, hassle-free transfer from airports across Europe? Visit <a href=https://transferme24.com/>https://transferme24.com/</a> where you'll find the best transfer prices when you book online. We offer a fixed rate. Learn all about our fleet and personalized service on our website. Our drivers monitor your flights to ensure you're met on time and safely transported to your destination.
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.