PHP use$_ SERVER[‘PHP_ Self ‘] to get the current page address and its security issues

Knowledge map advanced must read: read how large-scale map data efficient storage and retrieval>>>


$_ SERVER[‘PHP_ Self ‘] indicates the location address of the current PHP file relative to the root directory of the website, which is related to document root

Suppose we have the following website$_ SERVER[‘PHP_ The results of self ‘] are as follows: :/php/index.php :/php/index.php :/php/index.php :/php/index.php/test/foo

Therefore, it can be used$_ SERVER[‘PHP_ Self ‘] it’s very convenient to get the address of the current page:

$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

Taking the above address as an example, the results are as follows:

The above is a simple way to get the current page URL of the HTTP protocol. Just note that the address does not contain the requested parameter (?) in the URL?And the following string). If you want to get the full URL address that contains the request parameters, use$_ SERVER[‘REQUEST_ URI’] 。

PHP $_ SERVER[‘PHP_ Self ‘] security

Due to the use of$_ SERVER[‘PHP_ Self ‘] can easily obtain the current page address, so some programmers like to use the following method when submitting form data to the current page for processing:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

Suppose the page address is:

The HTML code of the form is as follows:

<form method="post" action="/php/index.php">

This code is correct, but when the access address becomes:

The page is executed normally, and the HTML code of the form becomes:

<form method="post" action="/php/index.php/test/foo">

Obviously, this code is not what we expected. Attackers can add attack code at will after the URL. To solve this problem, we can:

Using htmlentities ($_ SERVER[‘PHP_ Self ‘]$_ SERVER[‘PHP_ Self ‘], so that the possible malicious code in the URL can be converted into HTML code for display and cannot be executed

If possible, use$_ SERVER[‘SCRIPT_ [name ‘] or$_ SERVER[‘REQUEST_ Uri ‘] substitution$_ SERVER[‘PHP_ SELF’]

In the common code$_ SERVER[‘PHP_ Self ‘]:

$phpfile = basename(__FILE__);
$_SERVER['PHP_SELF'] = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], $phpfile)).$phpfile;

Similar Posts: