What is htmlspecialchars ($_ server php_self?

htmlspecialchars replaces characters with special meaning in HTML with &-escaped entities. So, for example, ' becomes '. It doesn't turn %22 into ", however, because %22 has no special meaning in HTML, so it's safe to display it without modification.

If you want a form to be handled by the same URL that is used to display it, always use action="" rather than action= or action=.

As you've already figured out, there are serious risks of cross-site scripting [XSS] if you use either of the $_SERVER variables, because they contain user input and therefore cannot be trusted. So, unless you have a good reason that you need to tweak the URL somehow, just use action="".

In this article shows the usage of PHP_SELF variable and how to avoid PHP_SELF exploits.

What is PHP_SELF variable?

PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file [from the root folder]. You can use this variable in the action field of the FORM. There are also certain exploits that you need to be aware of. We shall discuss all these points in this article. We will now see some examples. echo $_SERVER['PHP_SELF'];

a] Suppose your php file is located at the address: //www.yourserver.com/form-action.php

In this case, PHP_SELF will contain: "/form-action.php"

b] Suppose your php file is located at the address: //www.yourserver.com/dir1/form-action.php

For this URL, PHP_SELF will be : "/dir1/form-action.php"

Using the PHP_SELF variable in the action field of the form

A common use of PHP_SELF variable is in the action field of the tag. The action field of the FORM instructs where to submit the form data when the user presses the “submit” button. It is common to have the same PHP page as the handler for the form as well.

However, if you provide the name of the file in the action field, in case you happened to rename the file, you need to update the action field as well; or your forms will stop working.

Using PHP_SELF variable you can write more generic code which can be used on any page and you do not need to edit the action field.

Consider, you have a file called form-action.php and want to load the same page after the form is submitted. The usual form code will be:





We can use the PHP_SELF variable instead of “form-action.php”. The code becomes:

Chủ Đề