Internet Windows Android

Sinless server php. Superglobal array $_SERVER

$HTTP_SERVER_VARS [deleted]

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

$_SERVER -- $HTTP_SERVER_VARS [deleted]Information about the server and execution environment

Description

The $_SERVER variable is an array containing information such as script headers, paths, and locations. The entries in this array are created by the web server. There is no guarantee that every web server will provide any of them; the server may omit some of them or provide others not listed here. However, many of these variables are present in the » CGI/1.1 specification, so you can expect them to be implemented in your particular web server.

The $HTTP_SERVER_VARS variable contains the same initial information, but it is not superglobal. (Note that $HTTP_SERVER_VARS and $_SERVER are different variables, so PHP treats them accordingly). Also note that "long arrays" were removed in PHP 5.4.0, so $HTTP_SERVER_VARS no longer exists.

Indexes

You may (or may not) find any of the following elements in the $_SERVER array. Note that few, if any, items will be available (or really make a difference) if PHP is running on the command line.

"PHP_SELF" The name of the script file that is currently running, relative to the document root. For example, $_SERVER["PHP_SELF"] in the script at http://example.com/foo/bar.php would be /foo/bar.php . The __FILE__ constant contains the full path and file name of the current (that is, connected) file. If PHP is running on the command line, this variable contains the name of the script, starting with PHP 4.3.0. Previously it was not available."argv" An array of arguments passed to the script. When the script is run on the command line, it gives C-like access to command line options. When called via the GET method, this array will contain the query string."argc" Contains the number of parameters passed to the script (if launched on the command line)."GATEWAY_INTERFACE" Contains the version of the CGI specification used by the server; For example" CGI/1.1". "SERVER_ADDR" IP address of the server on which the current script is running."SERVER_NAME" The name of the host on which the current script is running. If the script is running on a virtual host, this will contain the name defined for that virtual host."SERVER_SOFTWARE" The server identification string specified in the headers when a response to a request occurs."SERVER_PROTOCOL" The name and version of the information protocol through which the page was requested; For example " HTTP/1.0"; "REQUEST_METHOD" What method was used to request the page; For example " GET", "HEAD", "POST", "PUT".

Comment:

The PHP script exits after sending the headers (that is, after performing any output without buffering the output), if the request was made using the method HEAD.

"REQUEST_TIME" Timestamp of the start of the request. Available starting from PHP 5.1.0."REQUEST_TIME_FLOAT" Timestamp of the start of the request, accurate to microseconds. Available starting from PHP 5.4.0."QUERY_STRING" The query string, if any, that retrieved the page."DOCUMENT_ROOT" The document root directory in which the current script is executed is exactly the one specified in the server configuration file."HTTP_ACCEPT" Header content Accept: from the current request, if there is one." HTTP_ACCEPT_CHARSET " Header content Accept-Charset: from the current request, if there is one. For example: " iso-8859-1,*,utf-8". " HTTP_ACCEPT_ENCODING " Header content Accept-Encoding: gzip". " HTTP_ACCEPT_LANGUAGE " Header content Accept-Language: from the current request, if there is one. For example: " en". "HTTP_CONNECTION" Header content Connection: from the current request, if there is one. For example: " Keep-Alive". "HTTP_HOST" Header content Host: from the current request, if there is one."HTTP_REFERER" The address of the page (if any) that brought the user's browser to this page. This header is set by the user's web browser. Not all browsers install it and some allow you to change the contents of the HTTP_REFERER header as an additional feature. In a word, he really cannot be trusted." HTTP_USER_AGENT " Header content User-Agent: from the current request, if there is one. This line contains the browser that the user used to request this page. A typical example is the line: Mozilla/4.5 (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with the function get_browser() to adapt the output of your page to the capabilities of the user's browser"HTTPS" Accepts a non-empty value if the request was made via the HTTPS protocol.

Comment: Note that when using ISAPI with IIS the value will be off, if the request was not made via HTTPS.

"REMOTE_ADDR" The IP address from which the user is viewing the current page."REMOTE_HOST" The remote host from which the user is viewing the current page. Reverse DNS lookup is based on the value of the REMOTE_ADDR variable.

Comment: Your web server must be configured to create this variable. For example, in Apache you need the presence of the directive HostnameLookups On in the httpd.conf file so that this variable is created. see also gethostbyaddr().

"REMOTE_PORT" The port on the remote machine that is used to communicate with the web server."REMOTE_USER" Authenticated user."REDIRECT_REMOTE_USER" The authenticated user if the request was redirected internally."SCRIPT_FILENAME"

The absolute path to the script that is currently executing.

Comment:

If the script is run on the command line (CLI) using a relative path such as file.php or ../file.php , the $_SERVER["SCRIPT_FILENAME"] variable will contain the relative path specified by the user.

"SERVER_ADMIN" This variable gets its value (for Apache) from a directive in the server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host."SERVER_PORT" The port on the server computer that the web server uses to connect. For default settings, the value will be " 80 "; using SLL, for example, this value will be as configured for secure HTTP connections.

Comment: To get a physical (real) port in Apache 2, you need to install UseCanonicalName = On And UseCanonicalPhysicalPort = On, otherwise this value may be replaced and not return the real value of the physical port. Relying on this value is unsafe in the context of applications that require enhanced security.

"SERVER_SIGNATURE" A string containing the server version and virtual host name that is added to server-generated pages if enabled."PATH_TRANSLATED" Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Comment: As of PHP 4.3.2, the PATH_TRANSLATED variable is no longer set implicitly in the Apache 2 SAPI, compared to Apache version 1 where it was set to the same value as the SCRIPT_FILENAME variable when not in use by Apache. This change was made to comply with the CGI specification, where the PATH_TRANSLATED variable should only exist when PATH_INFO is defined. Apache 2 users can use the directive AcceptPathInfo = On in the httpd.conf configuration file to set the PATH_INFO variable.

"SCRIPT_NAME" Contains the path to the currently executing script. This is useful for pages that need to point to themselves. The __FILE__ constant contains the full path and name of the current (i.e. included) file."REQUEST_URI" The URI that was passed in order to access this page. For example, " /index.html". "PHP_AUTH_DIGEST" When performing HTTP Digest authentication, this variable is assigned the "Authorization" header, which is sent by the client (this must then be used for appropriate validation)."PHP_AUTH_USER" When HTTP authentication is performed, this variable is set to the username provided by the user."PHP_AUTH_PW" When HTTP authentication is performed, this variable is set to the password provided by the user."AUTH_TYPE" When HTTP authentication is performed, this variable is set to the authentication type that is being used."PATH_INFO" Contains any user-supplied path contained after the script name but before the query string, if available. For example, if the current script is requested by the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar , then the $_SERVER["PATH_INFO"] variable will contain /some/stuff?>

The result of running this example will be something like this.

First, we will improve the registration page by adding the ability to upload an avatar. The source image must be in jpg, gif or png format. It should also be no more than 2 MB. Don't worry, after it is compressed by the script, the avatar size will be about 3 kb and jpg format. Open the page reg.php and add it in the tag < form> line enctype="multipart/form-data", as in the example:


Registration










Now let's save reg.php

2.Then you need to create another field in the table users. Let's go to phpmyadmin, select the desired database and table.


We set all the values ​​as in the figure:

The path to the avatar will be recorded in this field, and it will be saved in a separate folder, let’s call it “avatars”. The folder will be located in the same directory as the rest of the script files.

3.Go to the file save_ user. php and add the following code after removing spaces from the login and password:

//remove extra spaces
$login = trim($login);

// add new ********************************************

//add a check for the length of the login and password
if (strlen($login)< 3 or strlen($login) > 15) {
exit("Login must consist of at least 3 characters and no more than 15.");
}
if (strlen($password)< 3 or strlen($password) > 15) {
exit("Password must be at least 3 characters and no more than 15.");
}

if (!empty($_POST["fupload"])) //check if the user has sent the image
{
$fupload=$_POST["fupload"]; $fupload = trim($fupload);
if ($fupload =="" or empty($fupload)) (
unset($fupload);// if the $fupload variable is empty, then delete it
}
}
if (!isset($fupload) or empty($fupload) or $fupload =="")
{
//if the variable does not exist (the user did not send an image), then assign it a pre-prepared picture with the inscription “no avatar”
$avatar = "avatars/net-avatara.jpg"; //you can draw net-avatara.jpg or take it from the source
}
else
{
//otherwise - load the user's image
$path_to_90_directory = "avatars/";//folder where the initial image and its compressed copy will be loaded

If(preg_match("/[.](JPG)|(jpg)|(gif)|(GIF)|(png)|(PNG)$/",$_FILES["fupload"]["name"])) //checking the source image format
{
$filename = $_FILES["fupload"]["name"];
$source = $_FILES["fupload"]["tmp_name"];
$target = $path_to_90_directory . $filename;
move_uploaded_file($source, $target);//uploading the original to the folder $path_to_90_directory
if(preg_match("/[.](GIF)|(gif)$/", $filename)) (
$im = imagecreatefromgif($path_to_90_directory.$filename) ; //if the original was in gif format, then create an image in the same format. Necessary for subsequent compression
}
if(preg_match("/[.](PNG)|(png)$/", $filename)) (
$im = imagecreatefrompng($path_to_90_directory.$filename) ;//if the original was in png format, then create the image in the same format. Necessary for subsequent compression
}

If(preg_match("/[.](JPG)|(jpg)|(jpeg)|(JPEG)$/", $filename)) (
$im = imagecreatefromjpeg($path_to_90_directory.$filename); //if the original was in jpg format, then create an image in the same format. Necessary for subsequent compression
}
//CREATION OF A SQUARE IMAGE AND ITS SUBSEQUENT COMPRESSION TAKEN FROM THE SITE www.codenet.ru
// Create a 90x90 square
// dest - the resulting image
// w - image width
// ratio - proportionality coefficient
$w = 90; // square 90x90. Can be supplied in other sizes.
// create the original image based on
// source file and determine its size
$w_src = imagesx($im); //calculate the width
$h_src = imagesy($im); //calculate the height of the image
// create an empty square image
// truecolor is important!, otherwise we will have an 8-bit result
$dest = imagecreatetruecolor($w,$w);
// cut out the square center along x if the photo is horizontal
if ($w_src>$h_src)
imagecopyresampled($dest, $im, 0, 0,
round((max($w_src,$h_src)-min($w_src,$h_src))/2),
0, $w, $w, min($w_src,$h_src), min($w_src,$h_src));
// cut out the square top along y,
// if the photo is vertical (although you can also use the middle)
if ($w_src<$h_src)
imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $w,
min($w_src,$h_src), min($w_src,$h_src));
// square image is scaled without clipping
if ($w_src==$h_src)
imagecopyresampled($dest, $im, 0, 0, 0, 0, $w, $w, $w_src, $w_src);
$date=time(); //calculate the current time.
imagejpeg($dest, $path_to_90_directory.$date.".jpg");//save the image in jpg format to the desired folder, the name will be the current time. Made to prevent avatars from having the same names.
//why jpg? It takes up very little space + the animation of the GIF image, which distracts the user, is destroyed. It’s not very pleasant to read his comment when you notice some movement out of the corner of your eye.
$avatar = $path_to_90_directory.$date.".jpg";//put the path to the avatar into the variable.
$delfull = $path_to_90_directory.$filename;
unlink ($delfull);//delete the original uploaded image, we no longer need it. The task was to get a miniature.
}
else
{
//in case of format mismatch, issue a corresponding message
exit("The avatar must be in the format JPG,GIF or PNG");
}
//end of the loading process and assigning the $avatar variable the address of the loaded ava
}



// added new ************************************************
// Next comes everything from the first part of the article, but you need to add a change to the database query.
//connect to the database
// check for the existence of a user with the same login
$result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
if (!empty($myrow["id"])) (
exit("Sorry, the login you entered is already registered. Please enter another login.");
}
// if this is not the case, then save the data
$result2 = mysql_query("INSERT INTO users (login,password,avatar) VALUES("$login","$password","$avatar")");
// Check if there are errors
if ($result2=="TRUE")
{
echo "You have successfully registered! Now you can enter the site. Home page";
}
else(
echo "Error! You are not registered.";
}
?>

4. You need to add one table to the same database. It will store IP addresses that made errors when logging in. This way we can limit access to those who made mistakes more than three times in a row for about 15 minutes. I think programs that select passwords will have to tinker for a long time.
Let's go to phpmyadmin and create a new table with 3 fields:


ip - IP address.
date - date of unsuccessful login for the last 15 minutes for the user with this ip. col - the number of errors over the last 15 minutes for the user with this ip.
Great! Done, now let’s change the login and password verification file, because now our password is encrypted. Open testreg.php and delete everything beyond removing spaces from the login and password. Next we add the following code:

//remove extra spaces
$login = trim($login);
$password = trim($password);

// replace with a new one**************************************************
// connect to the database
include("bd.php");// the bd.php file must be in the same folder as all the others, if it is not then just change the path
// mini-check for password selection
$ip=getenv("HTTP_X_FORWARDED_FOR");
if (empty($ip) || $ip=="unknown") ( $ip=getenv("REMOTE_ADDR"); )//extract ip
mysql_query ("DELETE FROM oshibka WHERE UNIX_TIMESTAMP() - UNIX_TIMESTAMP(date) > 900");//delete the IP addresses of users who made a mistake when logging in after 15 minutes.
$result = mysql_query("SELECT col FROM oshibka WHERE ip="$ip"",$db); // retrieve from the database the number of unsuccessful login attempts over the last 15 for a user with a given ip
$myrow = mysql_fetch_array($result);
if ($myrow["col"] > 2) (
//if there are more than two errors, i.e. three, then we issue a message.
exit("You entered your username or password incorrectly 3 times. Please wait 15 minutes before trying again.");
}
$password = md5($password);//encrypt the password
$password = strrev($password);// for reliability, add reverse
$password = $password."b3p6f";
//you can add a few of your own characters to your taste, for example, by entering "b3p6f". If this password is hacked by brute force on the same md5 server, then obviously nothing good will come of it. But I advise you to put other characters, maybe at the beginning of the line or in the middle.
//In this case, it is necessary to increase the length of the password field in the database. The encrypted password may be much larger.

$result = mysql_query("SELECT * FROM users WHERE login="$login" AND password="$password"",$db); //retrieve from the database all data about the user with the entered login and password
$myrow = mysql_fetch_array($result);
if (empty($myrow["id"]))
{
//if the user with the entered login and password does not exist
//We make a record that this ip could not log in.
$select = mysql_query("SELECT ip FROM oshibka WHERE ip="$ip"");
$tmp = mysql_fetch_row($select);
if ($ip == $tmp) (//check if the user is in the "oshibka" table
$result52 = mysql_query("SELECT col FROM oshibka WHERE ip="$ip"",$db);
$myrow52 = mysql_fetch_array($result52);
$col = $myrow52 + 1;//add one more unsuccessful login attempt
mysql_query("UPDATE error SET col=$col,date=NOW() WHERE ip="$ip"");
}
else(
mysql_query("INSERT INTO oshibka (ip,date,col) VALUES ("$ip",NOW(),"1")");
//if there were no errors in the last 15 minutes, then insert a new entry into the "oshibka" table
}

exit("Sorry, the username or password you entered is incorrect.");
}
else(
nbsp; //if the passwords match, then we launch a session for the user! You can congratulate him, he got in!
$_SESSION["password"]=$myrow["password"];
$_SESSION["login"]=$myrow["login"];
$_SESSION["id"]=$myrow["id"];//this data is used very often, so the logged in user will “carry it with him”

//Next we save the data in cookies for subsequent login.
//ATTENTION!!! DO THIS AT YOUR DISCRETION AS THE DATA IS STORED IN COOKIES WITHOUT ENCRYPTION
if ($_POST["save"] == 1) (
//If the user wants his data to be saved for subsequent login, then we save it in his browser cookies
setcookie("login", $_POST["login"], time()+9999999);
setcookie("password", $_POST["password"], time()+9999999);
}}
echo " ";//we redirect the user to the main page, where we will notify him of successful login
?>

5. We will completely change the main page. It is necessary to display the user’s avatar on it, display a link to log out of the account and add a checkbox to remember the password when logging in.
Index.php

// the whole procedure works in sessions. It is where the user's data is stored while he is on the site. It is very important to launch them at the very beginning of the page!!!
session_start();
include("bd.php");// the bd.php file must be in the same folder as all the others, if it is not then just change the path
if (!empty($_SESSION["login"]) and !empty($_SESSION["password"]))
{
//if there is a login and password in the sessions, then check them and retrieve the avatar
$login = $_SESSION["login"];
$password = $_SESSION["password"];
$result = mysql_query("SELECT id,avatar FROM users WHERE login="$login" AND password="$password"",$db);
$myrow = mysql_fetch_array($result);
//extract the necessary user data
}
?>


Home page


Home page

if (!isset($myrow["avatar"]) or $myrow["avatar"]=="") (
//check if user data has been extracted from the database. If not, then he is not logged in, or the password in the session is incorrect. We display a login window. But we will not display it for those who come in, they no longer need it.
print<<


HERE;

If (isset($_COOKIE["login"])) //is there a variable with login in COOKIE. It should be if the user clicked on the “Remember me” checkbox during the previous login
{
//if yes, then insert its value into the form. In this case, the user is shown that his login has already been entered in the required column
echo " value="".$_COOKIE["login"]."">";
}

print<<




HERE;

If (isset($_COOKIE["password"]))//whether there is a variable with a password in the COOKIE. It should be if the user clicked on the “Remember me” checkbox during the previous login
{
//if yes, then insert its value into the form. In this case, the user is shown that his password has already been entered in the required column
echo " value="".$_COOKIE["password"]."">";
}

Print<<



Remember me.






Register



You are logged in as a guest

HERE;
}
else
{
//if the login is successful, the user is given everything below between the asterisks.

print<<
You are logged into the site as $_SESSION (exit)


This link is only available to registered users

Your avatar:




HERE;

//************************************************************************************
//if the login is successful, the user is given everything that is located ABOVE between the asterisks.
}
?>



6. It is necessary to make it possible for logged in users to log out. There was already a link to exit on the main page. But this file does not exist yet. So let's create a new file exit.php with code:

session_start();
if (empty($_SESSION["login"]) or empty($_SESSION["password"]))
{
//if there is no session with login and password, then this file was accessed by a non-logged in user. He doesn't belong here. We issue an error message and stop the script
exit ("Access to this page is allowed only to registered users. If you are registered, then log in to the site using your username and password
Home page");
}

unset($_SESSION["password"]);
unset($_SESSION["login"]);
unset($_SESSION["id"]);// destroy variables in sessions
exit(" ");
// send the user to the main page.
?>

OK it's all over Now! Enjoy it for your health! Good luck!

The $_SERVER["DOCUMENT_ROOT"] element contains the path to the root directory of the server; if the script is executed in a virtual host, this element specifies the path to the root directory of the virtual host. Those. in the httpd.conf configuration file, the virtual host has a DocumentRoot directive set to "D:/main", the $_SERVER["DOCUMENT_ROOT"] element will contain the value "D:main".

$_SERVER["HTTP_ACCEPT"] element

The $_SERVER["HTTP_ACCEPT"] element describes the client's document type preferences. The contents of this element are retrieved from the Accept HTTP header sent by the client to the server. The content of this header might look like this

Image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/msword, */*

The Accept header allows you to specify the media type that the client prefers to receive in response to its request. This header lets the server know that the response is limited to a small set of preferred types.

The * symbol is used to group types in a media series. For example, the symbol */* specifies the use of all types, and the notation type/* specifies the use of all subtypes of the selected type type.

Comment

Media types are separated by commas.

Each media series is also characterized by an additional set of parameters. One of them is the so-called relative preference coefficient q, which takes values ​​from 0 to 1, respectively, from less preferred types to more preferred ones. Using multiple q parameters allows the client to tell the server its relative preference for a particular media type.

Comment

By default, the q parameter is 1. It is also separated from the media type by a semicolon.

Example of an Accept header:

Accept: audio/*; q=0.2, audio/basic

In this header, the first type is audio/*, which includes all musical documents and is characterized by a preference coefficient of 0.2. Separated by commas, the audio/basic type is indicated, for which the preference coefficient is not specified and takes a default value of one. Quoting this heading can be interpreted as follows: “I prefer the audio/basic type, but I can also send documents of any other audio type, if available, after reducing the preference factor by more than 80%.”

The example may be more complex.

Accept: text/plain; q=0.5, text/html,
text/x-dvi; q=0.8, text/x-c

Comment

Note that the $_SERVER["HTTP_ACCEPT"] element contains exactly the same information, but without the initial Accept header.

This header is interpreted as follows: The document types text/html and text/x-c are preferred, but if these are not available, then the client making this request will prefer text/x-dvi, and, if not available, it may accept the type text/ plain.

Element $_SERVER["HTTP_ACCEPT_LANGUAGE"]

The $_SERVER["HTTP_ACCEPT_LANGUAGE"] element describes the client's language preference. This information is extracted from the Accept-Language HTTP header that the client sends to the server. The following example can be given:

Accept-Language: ru, en; q=0.7

Which can be interpreted as follows: the client prefers the Russian language, but if it is not available, he agrees to accept documents in English. The $_SERVER["HTTP_ACCEPT_LANGUAGE"] element will contain exactly the same information, but without the Accept-Language header:

Ru, en; q=0.7

The contents of the $_SERVER["HTTP_ACCEPT_LANGUAGE"] element can be used to determine the nationality of visitors. However, the results will be approximate, since many users use English versions of browsers, which will notify the server that the visitor prefers only one language - English.

Element $_SERVER["HTTP_HOST"]

The $_SERVER["HTTP_HOST"] element contains the server name, which usually matches the domain name of the site located on the server. Typically, the name specified in this parameter is the same as the name $_SERVER["SERVER_NAME"]. The parameter contains only the domain name without the protocol name (http://), i.e.

www.sofftime.ru

Element $_SERVER["HTTP_REFERER"]

The $_SERVER["HTTP_REFERER"] element contains the address of the page from which the visitor came to this page. The transition must be carried out via a link. Let's create two pages index.php and page.php.

index.php page

echo "Link to PHP page
"
;
$_SERVER["HTTP_REFERER"]
?>

The page.php page will have similar content, but the link will point to the index.php page.

Page page.php

echo "Link to PHP page
"
;
echo "Contents of $_SERVER ["HTTP_REFERER"] - " .
$_SERVER["HTTP_REFERER"]
?>

When moving from one page to another, the address of the page from which the transition was made will be displayed under the link.

Element $_SERVER["HTTP_USER_AGENT"]

The $_SERVER["HTTP_USER_AGENT"] element contains information about the type and version of the visitor's browser and operating system.

Here is a typical content of this line: "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)". The presence of the substring "MSIE 6.0" indicates that the visitor is viewing the page using Internet Explorer version 6.0. The line "Windows NT 5.1" indicates that the operating system is Windows XP.

Comment

For Windows 2000, the $_SERVER["HTTP_USER_AGENT"] element looks like this: "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"), while for Windows XP it looks like "Mozilla/4.0 (compatible; MSIE 6.0 ;Windows NT 5.1)".

If the visitor uses the Opera browser, the content of $_SERVER["HTTP_USER_AGENT"] might look like this: "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.04 ". The substring "MSIE 6.0" is also present here, indicating that the Opera browser is compatible with the Internet Explorer browser and uses the same Windows dynamic libraries. Therefore, when analyzing the string returned by the browser, you should keep in mind that Internet Explorer refers to a string containing the substring "MSIE 6.0" and not containing the substring "Opera". In addition, from this line we can conclude that the user is using the Windows 98 operating system.

Comment

The Firefox browser user agent might look like this: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8) Gecko/20051111 Firefox/1.5.

When using the Netscape browser, the content of the $_SERVER["HTTP_USER_AGENT"] element might look like this: "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624 Netscape/7.1". Belonging to this browser can be determined by the presence of the substring "Netscape". In addition, you can find out that the visitor accesses the Internet using an operating version of Linux, with a kernel optimized for Pentium IV, while in the X-Window graphical shell. This mechanism is convenient to use to collect statistical information, which allows designers to optimize pages for the most common browsers.

Element $_SERVER["REMOTE_ADDR"]

The $_SERVER["REMOTE_ADDR"] element contains the client's IP address. When testing on a local machine, this address will be equal to 127.0.0.1. However, when testing on the network, the variable will return the IP address of the client or the last proxy server through which the client reached the server. If the client uses a proxy server, you can find out its IP address using the HTTP_X_FORWARDED_FOR environment variable, the value of which can be obtained using the getenv() function.

Comment

Proxy servers are special intermediate servers that provide a special type of service: traffic compression, data encoding, adaptation for mobile devices, etc. Among the many proxy servers, there are so-called anonymous proxy servers, which allow you to hide the client’s true IP address; such servers do not return the HTTP_X_FORWARDED_FOR environment variable.

Retrieving the HTTP_X_FORWARDED_FOR environment variable

echo getenv(HTTP_X_FORWARDED_FOR);
?>

Element $_SERVER["SCRIPT_FILENAME"]

The $_SERVER["SCRIPT_FILENAME"] element contains the absolute path to the file from the disk root. So, if the server is running the Windows operating system, then this path may look like this: “d:main estindex.php”, i.e. the path is specified from the disk; in a UNIX-like operating system, the path is specified from the root directory /, for example "/var/share/www/test/index.php".

Element $_SERVER["SERVER_NAME"]

The $_SERVER["SERVER_NAME"] element contains the server name, which usually matches the domain name of the site located on it. For example,

www.site

The content of the $_SERVER["SERVER_NAME"] element is often the same as the content of the $_SERVER["HTTP_HOST"] element. In addition to the server name, the superglobal array $_SERVER allows you to find out a number of server parameters, for example, the server IP address, the listening port, which Web server is installed and the HTTP protocol version. This information is placed in the $_SERVER["SERVER_ADDR"], $_SERVER["SERVER_PORT"], $_SERVER["SERVER_SOFTWARE"] and $_SERVER["SERVER_PROTOCOL"] elements, respectively. Below is an example using these elements.

Using $_SERVER Array Elements

echo "Server name - " . $_SERVER["SERVER_NAME"]. "
" ;
echo "Server IP address - ". $_SERVER["SERVER_ADDR"]. "
" ;
echo "Server port - " . $_SERVER["SERVER_PORT"]. "
" ;
echo "Web server - " . $_SERVER["SERVER_SOFTWARE"]. "
" ;
echo "HTTP protocol version - ". $_SERVER["SERVER_PROTOCOL"]. "
" ;
?>

And this is what the client actually used as the "target host" of the request. SERVER_NAME is defined in the server configuration. Which one depends on what you need it for. Now you should understand that this is a client controlled value which is thus not reliable for use in business logic and the other is a server controlled value which is more reliable. However, you need to ensure that the web server has the correct SERVER_NAME configuration. Taking Apache HTTPD as an example, here's an excerpt from its documentation:

If ServerName is not specified, then the server attempts to infer the hostname by performing a reverse lookup on the IP address. If no port is specified in ServerName , then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using the ServerName directive.

Update: After checking Pekka's answer to your question, which contains a link to bobince's answer, that PHP will always return the HTTP_HOST value for SERVER_NAME, which contradicts my own experience with PHP 4.x + Apache HTTPD 1.2.x from a couple of years ago, I blew the dust off my current XAMPP on Windows XP (Apache HTTPD 2.2.1 with PHP 5.2.8), ran it, created a PHP page that prints both values, created a test Java application using URLConnection to change the Host header, and the tests taught me that this is indeed (incorrectly) the case.

After first suspecting PHP and digging into some PHP error reports regarding the subject, I found out that the root of the problem is in the web server being used, that it was incorrectly returning the HTTP Host header when SERVER_NAME was requested. So I dug into Apache HTTPD error reports using various keywords relatively subject and I finally found the related error. This behavior was introduced since Apache HTTPD 1.3. You need to set the UseCanonicalName directive on in the entry ServerName in httpd.conf (also check the warning at the bottom of the document!).

ServerName example.com UseCanonicalName on

This worked for me.

Generalized, SERVER_NAME is more reliable, but you dependent in the server configuration!

HTTP_HOST is the target host sent by the client. The user can manipulate the user freely. There is no need to send a request to your site asking for the HTTP_HOST value of www.stackoverflow.com.

SERVER_NAME comes from the VirtualHost server definition and is therefore considered more reliable. It can also be manipulated externally under certain conditions related to your web server setup. See this This SO question, which addresses the security aspects of both options.

You should not rely on it to be safe. However, which to use really depends on what you want to do. If you want to determine which domain your script is running on, you can safely use HTTP_HOST as long as invalid values ​​coming from an attacker can't break anything.

Note that if you want to use IPv6, you'll probably want to use HTTP_HOST rather than SERVER_NAME. If you enter http://[::1]/ , the environment variables will be as follows:

HTTP_HOST = [::1] SERVER_NAME = ::1

This means that if you do mod_rewrite, for example, you may get nasty results. SSL redirect example:

# SERVER_NAME will NOT work - Redirection to https://::1/ RewriteRule .* https://%(SERVER_NAME)/ # HTTP_HOST will work - Redirection to https://[::1]/ RewriteRule .* https: //%(HTTP_HOST)/

This ONLY applies if you are accessing the server without a hostname.

if you want to check via server.php or whatever you want to call with the following:

Then access all valid URLs for your site and test the difference.

It took me a while to understand what people mean by "SERVER_NAME is more reliable". I'm using a shared server and don't have access to virtual host directives. So I'm using mod_rewrite in .htaccess to map different HTTP_HOSTs in different directories. In this case, this HTTP_HOST value makes sense.

The situation is similar if you are using name-based virtual hosts: the ServerName directive inside a virtual host simply tells you what hostname will be mapped to that virtual host. The bottom line is that in both cases, the hostname provided by the client at the time of the request (HTTP_HOST) must match the name on the server, which is itself mapped to the directory. Whether the mapping is done against virtual host directives or htaccess mod_rewrite rules is secondary here. In these cases, HTTP_HOST will be the same as SERVER_NAME. I'm glad Apache is configured this way.

However, the situation is different for IP-based virtual hosts. In this case and only in this case, SERVER_NAME and HTTP_HOST can be different because the client now selects the server by IP, not by name. Indeed, there may be special configurations where this is important.

So from now on, I'll be using SERVER_NAME in case my code gets ported to these special configurations.

Assuming you have a simple setup (CentOS 7, Apache 2.4.x and PHP 5.6.20) and only one website (not assuming shared hosting)...

In the PHP sense, $_SERVER["SERVER_NAME"] is a PHP element registered in the $_SERVER superclass based on your Apache configuration (**ServerName** directive with UseCanonicalName On) in httpd.conf (whether from an enabled virtual host configuration file, anything, etc.). HTTP_HOST inferred from the HTTP host header. Consider this as user input. Filter and check before use.

Here's an example where I use $_SERVER["SERVER_NAME"] as a basis for comparison. The following method is on a specific child class that I called ServerValidator (child of Validator). ServerValidator checks six or seven elements in $_SERVER before using them.

When determining whether an HTTP request is a POST, I use this method.

Public function isPOST() ( return (($this->requestMethod === "POST") && // Ignore $this->hasTokenTimeLeft() && // Ignore $this->hasSameGETandPOSTIdentities() && // Ingore ($this ->httpHost === filter_input(INPUT_SERVER, "SERVER_NAME"))); )

By the time this method is called, all filtering and validation of the corresponding $_SERVER elements (and corresponding property sets) will have been done.

($this->httpHost === filter_input(INPUT_SERVER, "SERVER_NAME")

Verifies that the value of $_SERVER["HTTP_HOST"] (ultimately obtained from the requested HTTP host header) matches $_SERVER["SERVER_NAME"] .

Now I'm using superglobal talk to explain my example, but that's because some people aren't familiar with INPUT_GET , INPUT_POST and INPUT_SERVER in relation to filter_input_array() .

The bottom line is that I don't process POST requests on my server unless all four conditions are met. Hence, in terms of POST requests, failure to provide HTTP host header (presence checked for earlier) doom spells for strict browsers HTTP 1.0. Additionally, the requested host must match the value ServerName in httpd.conf, and by extension - the value $_SERVER("SERVER_NAME") in the $_SERVER supermaclon. Again, I would use INPUT_SERVER with PHP filter functions, but you were breaking my drift.

As stated by balusC, SERVER_NAME is not reliable and can be changed in the apache config, server server config and firewall that may be between you and the server.

The following function always returns the real host (user typed host) without the port, and it is almost foolproof:

Function getRealHost())( list($realHost,)=explode(":",$_SERVER["HTTP_HOST"]); return $realHost; )

share

JavaScript is blocked in your browser. Please enable JavaScript for the site to function!

Superglobal array $_SERVER

To array $_SERVER The PHP interpreter places the variables received from the server. Without these variables, it is difficult to organize full support for Web applications. Below is a description of the most important elements of the superglobal array $_SERVER.

Comment

  • View the complete list of $_SERVER array elements
  • you can either use the print_r() function, which prints an array dump, or using the phpinfo() function, which displays information about the PHP interpreter.

    Array ( => on => 200 => on => htmlweb.ru => https => 443 => close => Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot. html) => */* => beget=begetok; => gzip,deflate => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin = > => Apache/2.4.25 (Debian) mpm-itk/2.4.7-04 OpenSSL/1.0.2l => htmlweb.ru => 185.12.92.137 => 80 => 144.76.78.4 => /var/www/ htmlweb/data/www/htmlweb.ru => http => => /var/www/htmlweb/data/www/htmlweb.ru => [email protected]=>.php => 35242 => /php/function/$_server.php => CGI/1.1 => HTTP/1.0 => GET => => /php/function/%24_server.php => /index.php => /index.php => 1560059525.711 => 1560059525) 1

    $_SERVER[" DOCUMENT_ROOT"]

    The $_SERVER["DOCUMENT_ROOT"] element contains the path to the root directory of the server; if the script is executed in a virtual host, this element specifies the path to the root directory of the virtual host. Those. in the httpd.conf configuration file, the virtual host has a DocumentRoot directive set to "D:/main", the $_SERVER["DOCUMENT_ROOT"] element will contain the value "D:main".

    $_SERVER[" REMOTE_ADDR"]

    The $_SERVER["REMOTE_ADDR"] element contains the client's IP address. When testing on a local machine, this address will be equal to 127.0.0.1. However, when testing on the network, the variable will return the IP address of the client or the last proxy server through which the client reached the server. If the client uses a proxy server, you can find out its IP address using the HTTP_X_FORWARDED_FOR environment variable, the value of which can be obtained using the getenv() function.

    Comment

    Proxy servers are special intermediate servers that provide a special type of service: traffic compression, data encoding, adaptation for mobile devices, etc. Among the many proxy servers, there are so-called anonymous proxy servers, which allow you to hide the client’s true IP address; such servers do not return the HTTP_X_FORWARDED_FOR environment variable.

    Retrieving an environment variable HTTP_X_FORWARDED_FOR

    echo @getenv(HTTP_X_FORWARDED_FOR);

    $_SERVER[" SCRIPT_FILENAME"]

    The $_SERVER["SCRIPT_FILENAME"] element contains the absolute path to the file from the disk root. So, if the server is running the Windows operating system, then this path may look like this: “d:main estindex.php”, i.e. the path is specified from the disk; in a UNIX-like operating system, the path is specified from the root directory /, for example "/var/share/www/test/index.php".

    /var/www/htmlweb/data/www/site/index.php

    $_SERVER[" SERVER_NAME"]

    The $_SERVER["SERVER_NAME"] element contains the server name, which usually matches the domain name of the site located on it. For example,

    The content of the $_SERVER["SERVER_NAME"] element is often the same as the content of the $_SERVER["HTTP_HOST"] element. In addition to the server name, the superglobal array $_SERVER allows you to find out a number of server parameters, for example, the server IP address, the listening port, which Web server is installed and the HTTP protocol version. This information is placed in the $_SERVER["SERVER_ADDR"], $_SERVER["SERVER_PORT"], $_SERVER["SERVER_SOFTWARE"] and $_SERVER["SERVER_PROTOCOL"] elements, respectively. Below is an example using these elements.

    Using $_SERVER Array Elements

    echo "The server name is ".$_SERVER["SERVER_NAME"]."
    "; echo "The server IP address is ".$_SERVER["SERVER_ADDR"]."
    "; echo "Server port - ".$_SERVER["SERVER_PORT"]."
    "; echo "Web server - ".$_SERVER["SERVER_SOFTWARE"]."
    "; echo "HTTP protocol version - ".$_SERVER["SERVER_PROTOCOL"]."
    ";

    Server name - website
    Server IP address - 185.12.92.137
    Server port - 80
    Web server - Apache/2.4.25 (Debian) mpm-itk/2.4.7-04 OpenSSL/1.0.2l
    HTTP protocol version - HTTP/1.0

    $_SERVER[" REQUEST_METHOD"]

    The $_SERVER["REQUEST_METHOD"] element contains the request method that is used to call the script: GET or POST.

    Echo $_SERVER["REQUEST_METHOD"];

    $_SERVER[" QUERY_STRING"]

    The $_SERVER["QUERY_STRING"] element contains the parameters passed to the script if the query string is an address

    For example, when accessing:
    the $_SERVER["QUERY_STRING"] element will contain all the text after the "?" sign:

    Echo $_SERVER["QUERY_STRING"];

    id=1&test=wet&id_theme=512

    $_SERVER[" PHP_SELF"]

    The $_SERVER["PHP_SELF"] element contains the name of the script, starting from the root directory of the virtual host, i.e. if the query string is an address http://www.mysite.ru/test/index.php?id=1&test=wet&id_theme=512 then the $_SERVER["PHP_SELF"] element will contain the fragment "/test/index.php". Typically, the same fragment is placed in the $_SERVER["SCRIPT_NAME"] element.

    $_SERVER[" REQUEST_URI"]

    The $_SERVER["REQUEST_URI"] element contains the name of the script, starting from the root directory of the virtual host and parameters, i.e. if the query string is an address: http://www.mysite.ru/test/index.php?id=1&test=wet&id_theme=512 then the $_SERVER["REQUEST_URI"] element will contain the fragment "/test/index.php?id=1&test=wet&id_theme=512". In order to restore the full address in the script, which is placed in the query line, it is enough to use the combination of elements of the $_SERVER array presented below

    Full address to the script

    echo "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];