When you insert ANY variable into HTML, unless you want the browser to interpret the variable itself as HTML, it's best to use htmlspecialchars()
on it. Among other things, it prevents hackers from inserting arbitrary HTML in your page.
The value of $_SERVER['PHP_SELF']
is taken directly from the URL entered in the browser. Therefore if you use it without htmlspecialchars()
, you're allowing hackers to directly manipulate the output of your code.
For example, if I e-mail you a link to http://example.com/"><script>malicious_code_here()</script><span class="
and you have <form action="<?php echo $_SERVER['PHP_SELF'] ?>">
, the output will be:
<form action="http://example.com/"><script>malicious_code_here()</script><span class="">
My script will run, and you will be none the wiser. If you were logged in, I may have stolen your cookies, or scraped confidential info from your page.
However, if you used <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">
, the output would be:
<form action="http://example.com/"><script>cookie_stealing_code()</script><span class="">
When you submitted the form, you'd have a weird URL, but at least my evil script did not run.
On the other hand, if you used <form action="">
, then the output would be the same no matter what I added to my link. This is the option I would recommend.