PHP 8.2.20 Released!

$_SERVER

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

$_SERVERServer and execution environment information

Description

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the » CGI/1.1 specification, and are likely to be defined.

Note: When running PHP on the command line most of these entries will not be available or have any meaning.

In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named HTTP_ followed by the header name, capitalized and with underscores instead of hyphens. For example, the Accept-Language header would be available as $_SERVER['HTTP_ACCEPT_LANGUAGE'].

Indices

'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; e.g. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.

Note: Under Apache 2, UseCanonicalName = On and ServerName must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts.

'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; e.g. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; e.g. 'GET', 'HEAD', 'POST', 'PUT'.

Note:

PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTPS'
Set to a non-empty value if the script was queried through the HTTPS protocol.
'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based on the REMOTE_ADDR of the user.

Note: The web server must be configured to create this variable. For example in Apache HostnameLookups On must be set inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'REMOTE_USER'
The authenticated user.
'REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note:

If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web 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 machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.

Note: Under Apache 2, UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On must be set in order to get the physical (real) port, otherwise, this value can be spoofed, and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts.

'SERVER_SIGNATURE'
String containing the server version and virtual host name which are 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.

Note: Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When doing HTTP authentication this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.

Examples

Example #1 $_SERVER example

<?php
echo $_SERVER['SERVER_NAME'];
?>

The above example will output something similar to:

www.example.com

Notes

Note:

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

add a note

User Contributed Notes 50 notes

up
149
Vladimir Kornea
15 years ago
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.

2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.

3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:

<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>

The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.

Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
up
54
vcoletti at tiscali dot it
4 years ago
To list all the $_SERVER parameters, simply do:

foreach ($_SERVER as $parm => $value) echo "$parm = '$value'\n";

No need to list all possible keys of the array.
up
36
MarkAgius at markagius dot co dot uk
12 years ago
You have missed 'REDIRECT_STATUS'

Very useful if you point all your error pages to the same file.

File; .htaccess
# .htaccess file.

ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.

File; error-msg.php
<?php
$HttpStatus
= $_SERVER["REDIRECT_STATUS"] ;
if(
$HttpStatus==200) {print "Document has been processed and sent to you.";}
if(
$HttpStatus==400) {print "Bad HTTP request ";}
if(
$HttpStatus==401) {print "Unauthorized - Iinvalid password";}
if(
$HttpStatus==403) {print "Forbidden";}
if(
$HttpStatus==500) {print "Internal Server Error";}
if(
$HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

?>
up
38
Lord Mac
14 years ago
An even *more* improved version...

<?php
phpinfo
(32);
?>
up
25
jonbarnett at gmail dot com
15 years ago
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:

If the browser sends an HTTP request header of:
X-Debug-Custom: some string

Then:

<?php
$_SERVER
['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>

There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.

Works in PHP5 on Apache with mod_php. Don't know if this is true from other environments.
up
23
pierstoval at example dot com
7 years ago
As PHP $_SERVER var is populated with a lot of vars, I think it's important to say that it's also populated with environment vars.

For example, with a PHP script, we can have this:

MY_ENV_VAR=Hello php -r 'echo $_SERVER["MY_ENV_VAR"];'

Will show "Hello".

But, internally, PHP makes sure that "internal" keys in $_SERVER are not overriden, so you wouldn't be able to do something like this:

REQUEST_TIME=Hello php -r 'var_dump($_SERVER["REQUEST_TIME"]);'

Will show something like 1492897785

However, a lot of vars are still vulnerable from environment injection.

I created a gist here ( https://gist.github.com/Pierstoval/f287d3e61252e791a943dd73874ab5ee ) with my PHP configuration on windows with PHP7.0.15 on WSL with bash, the results are that the only "safe" vars are the following:

PHP_SELF
SCRIPT_NAME
SCRIPT_FILENAME
PATH_TRANSLATED
DOCUMENT_ROOT
REQUEST_TIME_FLOAT
REQUEST_TIME
argv
argc

All the rest can be overriden with environment vars, which is not very cool actually because it can break PHP applications sometimes...

(and I only tested on CLI, I had no patience to test with Apache mod_php or Nginx + PHP-FPM, but I can imagine that not a lot of $_SERVER properties are "that" secure...)
up
12
ywarnier at beeznest dot org
6 years ago
Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.

This happens, for example, when calling the page through a call to stream_context_create() with a HTTP header of 'request_fulluri' set to 1.

For example:

$http = ['request_fulluri' => 1, /* other params here */];
$context = stream_context_create(array( 'http' => $http ));
$fp = fopen($some_url, 'rb', false, $context);

When outputting $_SERVER['REQUEST_URI'] on the server at $some_url, you will get
https://some_url/some_script.php

Remove the request_fulluri => 1 option, and $_SERVER['REQUEST_URI'] gets back to its "normal":
/some_script.php

Apparently, request_fulluri is useful when using some proxy servers.

In this case, there is no proper way to "detect" if this option was set or not, and you should probably use a combination of other $_SERVER[] elements (like REQUEST_SCHEME, SERVER_NAME and SERVER_PORT) to determine if this was the case.

One quick (and improvable) way to detect it would be to compare the start of the REQUEST_URI with REQUEST_SCHEME:

$scheme = $_SERVER['REQUEST_SCHEME'] . '://';
if (strcmp(substr($_SERVER['REQUEST_URI'], 0, strlen($scheme)), $scheme) === 0) {
// request_fulluri was set
}
up
12
chris at ocproducts dot com
7 years ago
Guide to absolute paths...

Data: __FILE__
Data type: String
Purpose: The absolute pathname of the running PHP file, including the filename.
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: __DIR__
Data type: String
Purpose: The absolute pathname to the running PHP file, excluding the filename
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['SCRIPT_FILENAME']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: Not set on all PHP environments, may need setting by copying from __FILE__ before other files are included.
Caveat: Symbolic links are not pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Caveat: "Filename" makes you think it is just a filename, but it really is the full absolute pathname. Read the identifier as "Script's filesystem (path)name".
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['PATH_TRANSLATED']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: It's probably not set, best to just not use it. Just use realpath($_SERVER['SCRIPT_FILENAME']) (and be aware that itself may need to have been emulated).
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['DOCUMENT_ROOT']
Data type: String
Purpose: Get the absolute path to the web server's document root. No trailing slash.
Caveat: Don't trust this to be set, or set correctly, unless you control the server environment.
Caveat: May or may not have symbolic links pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.

Note that if you call "php --info" on the command line then naturally some of these settings are going to be blank, as no PHP file is involved.
up
4
Daniels118
2 years ago
If you need to know the protocol (http or https) used by the client, then the $_SERVER['HTTPS'] variable may not actually report the truth if your server is behind a proxy or a load balancer (In fact the client could connect to the load balancer using https, and then the load balancer forward the request to the server using http).
If the proxy/load balancer is correctly configured it could send the original request protocol in a header, and you will find it in the $_SERVER[HTTP_X_FORWARDED_PROTO] variable.
up
20
Richard York
14 years ago
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

["_SERVER"]=>
array(24) {
["MANPATH"]=>
string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
["TERM"]=>
string(11) "xterm-color"
["SHELL"]=>
string(9) "/bin/bash"
["SSH_CLIENT"]=>
string(20) "127.0.0.1 41242 22"
["OLDPWD"]=>
string(60) "/Library/WebServer/Domains/www.example.com/private"
["SSH_TTY"]=>
string(12) "/dev/ttys000"
["USER"]=>
string(5) "username"
["MAIL"]=>
string(15) "/var/mail/username"
["PATH"]=>
string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
["PWD"]=>
string(56) "/Library/WebServer/Domains/www.example.com/www"
["SHLVL"]=>
string(1) "1"
["HOME"]=>
string(12) "/Users/username"
["LOGNAME"]=>
string(5) "username"
["SSH_CONNECTION"]=>
string(31) "127.0.0.1 41242 10.0.0.1 22"
["_"]=>
string(12) "/usr/bin/php"
["__CF_USER_TEXT_ENCODING"]=>
string(9) "0x1F5:0:0"
["PHP_SELF"]=>
string(10) "Shell.php"
["SCRIPT_NAME"]=>
string(10) "Shell.php"
["SCRIPT_FILENAME"]=>
string(10) "Shell.php"
["PATH_TRANSLATED"]=>
string(10) "Shell.php"
["DOCUMENT_ROOT"]=>
string(0) ""
["REQUEST_TIME"]=>
int(1247162183)
["argv"]=>
array(1) {
[0]=>
string(10) "Shell.php"
}
["argc"]=>
int(1)
}
up
15
krinklemail at gmail dot com
11 years ago
If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group.

They are still accessible, but only if the request was a POST request. When it is, it'll be available as:
$_SERVER['CONTENT_LENGTH']
$_SERVER['CONTENT_TYPE']

[1] https://www.ietf.org/rfc/rfc3875
up
11
chris at ocproducts dot com
7 years ago
Guide to URL paths...

Data: $_SERVER['PHP_SELF']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info (see $_SERVER['PATH_INFO']) and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['SCRIPT_NAME']
Data type: String
Purpose: The URL path name of the current PHP file, excluding path-info and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Caveat: Not set on all PHP environments, may need setting via preg_replace('#\.php/.*#', '.php', $_SERVER['PHP_SELF']).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['REDIRECT_URL']
Data type: String
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['REQUEST_URI']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info and including URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL). *
*: I've seen at least one situation where this is not true (there was another $_SERVER variable to use instead supplied by the URL rewriter), but the author of the URL rewriter later fixed it so probably fair to dismiss this particular note.
Caveat: Not set on all PHP environments, may need setting via $_SERVER['REDIRECT_URL'] . '?' . http_build_query($_GET) [if $_SERVER['REDIRECT_URL'] is set, and imperfect as we don't know what GET parameters were originally passed vs which were injected in the URL rewrite] --otherwise-- $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['PATH_INFO']
Data type: String
Purpose: Find the path-info, which is data after the .php filename in the URL call. It's a strange concept.
Caveat: Some environments may not support it, it is best avoided unless you have complete server control
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.
up
10
Tonin
15 years ago
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive. If it is On, this variable will always have the apache ServerName value. If it is Off, it will have the value given by the headers sent by the browser.

Depending on what you want to do the content of this variable, put in On or Off.
up
8
Stefano (info at sarchittu dot org)
13 years ago
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).

The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen

<?php
$conflen
=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>

$host will finally contain the absolute path.
up
12
steve at sc-fa dot com
14 years ago
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
up
4
Mark Simon
4 years ago
So near, and yet so far …

$_SERVER has nearly everything you need to know about the current web page environment. Something which would have been handy is easy access to the protocol and the actual web root.

For the protocol, you may or may not have $_SERVER['HTTPS'] and it may or may not be empty. For the web root, $_SERVER['DOCUMENT_ROOT'] depends on the server configuration, and doesn’t work for virtual hosts.

For practical purposes, I normally include something like the following in my scripts:

<?php
// Web Root
// Usage: include("$root/includes/something.inc.php");
$root = $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['SCRIPT_FILENAME']);

// Host & Protocol
// Usage: $url = "$protocol://$host/images/something.jpg";
$host = $_SERVER['HTTP_HOST'];
$protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
?>
up
3
lemonostif at gmail dot com
4 years ago
PHP_SELF is a disgrace of a programmer's work. One of the most widespread PHP vulnerabilities since version 4 and the manual says nothing about the dangers. At least clarify that ITS VALUE CAN BE PROVIDED BY THE USER with capitals preferably if you want to make the internet a safer place...
up
6
php at isnoop dot net
14 years ago
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
up
6
info at mtprod dot com
15 years ago
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
up
5
jarrod at squarecrow dot com
14 years ago
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:

<?php
//Defines constants to use for "include" URLS - helps keep our paths clean

define("REGISTRY_CLASSES", $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");

define("STRING_BUILDER", REGISTRY_CLASSES. "stringbuilder.php");
define("SESSION_MANAGER", REGISTRY_CLASSES. "sessionmanager.php");
define("STANDARD_CONTROLS", REGISTRY_CONTROLS."standardcontrols.php");
?>

In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
up
2
centurianii at yahoo dot co dot uk
7 years ago
If you apply redirection in ALL your requests using commands at the Apache virtual host file like:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "!=/index.php"
RewriteRule "^/(.*)$" "index.php?$1" [NC,NE,L,QSA]
you should expect some deviations in your $_SERVER global.

Say, you send a url of: [hostname here]/a/b?x=1&y=2
which makes Apache to modify to: /index.php?/a/b?x=1&y=2

Now your $_SERVER global contains among others:
'REQUEST_URI' => '/a/b?x=1&y=2', it retains the initial url after the host
'QUERY_STRING' => 'a/b&x=1&y=2', notice how php replaces '?' with '&'
'SCRIPT_NAME' => '/index.php', as it was intended to be.

To test your $_SERVER global:
function serverArray(){
$arr = array();
foreach($_SERVER as $key=>$value)
$arr[] = '&nbsp;&nbsp;&nbsp;\'' . $key . '\' => \'' . (isset($value)? $value : '-') . '\'';
return @\sort($arr)? '$_SERVER = array(<br />' . implode($arr, ',<br />') . '<br />);' : false;
}
echo serverArray();
up
5
Tom
11 years ago
Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input.
up
4
pomat at live dot it
10 years ago
$_SERVER['DOCUMENT_ROOT'] may contain backslashes on windows systems, and of course it may or may not have a trailing slash (backslash).
I saw the following as an example of the proper way we're supposed to deal with this issue:

<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php');
?>

Ok, the latter may be used to access a file inside the parent directory of the document root, but actually does not properly address the issue.
In the end, don't warry about. It should be safe to use forward slashes and append a trailing slash in all cases.
Let's say we have this:

<?php
$path
= 'subdir/file.php';
$result = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
?>

On linux $result might be something like
1) "/var/www/subdir/file.php"
2) "/var/www//subdir/file.php"
String 2 is parsed the same as string 1 (have a try with command 'cd').

On windows $result might be something like
1) "C:/apache/htdocs/subdir/file.php"
2) "C:/apache/htdocs//subdir/file.php"
3) "C:\apache\htdocs/subdir/file.php"
4) "C:\apache\htdocs\/subdir/file.php"
All those strings are parsed as "C:\apache\htdocs\subdir\file.php" (have a try with 'cd').
up
6
chris
14 years ago
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
up
5
mirko dot steiner at slashdevslashnull dot de
14 years ago
<?php

// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1

foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
$pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
'(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
'(?P<quantifier>\d\.\d))?$/';

$splits = array();

printf("Lang:,,%s''\n", $lang);
if (
preg_match($pattern, $lang, $splits)) {
print_r($splits);
} else {
echo
"\nno match\n";
}
}

?>

example output:

Google Chrome 3.0.195.27 Windows xp

Lang:,,de-DE''
Array
(
[0] => de-DE
[primarytag] => de
[1] => de
[subtag] => DE
[2] => DE
)
Lang:,,de;q=0.8''
Array
(
[0] => de;q=0.8
[primarytag] => de
[1] => de
[subtag] =>
[2] =>
[quantifier] => 0.8
[3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
[0] => en-US;q=0.6
[primarytag] => en
[1] => en
[subtag] => US
[2] => US
[quantifier] => 0.6
[3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
[0] => en;q=0.4
[primarytag] => en
[1] => en
[subtag] =>
[2] =>
[quantifier] => 0.4
[3] => 0.4
)
up
0
Anonymous
17 minutes ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> </title>
</head>
<body>
<form>

</form>
</body>
</html>
up
0
Anonymous
17 minutes ago
<?php
// Database connection parameters
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "factory";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die(
"Connection failed: " . $conn->connect_error);
}

$minQuantity = $_POST['minQuantity'];
$sql = "SELECT product_code, product_name, quantity_in_stock FROM products WHERE quantity_in_stock >= ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $minQuantity);
$stmt->execute();
$result = $stmt->get_result();

if (
$result->num_rows > 0) {
echo
"<h1>Products with Minimum Quantity in Stock</h1>";
echo
"<table border='1'>";
echo
"<tr><th>Product Code</th><th>Product Name</th><th>Quantity in Stock</th></tr>";
while(
$row = $result->fetch_assoc()) {
echo
"<tr>";
echo
"<td>" . $row["product_code"] . "</td>";
echo
"<td>" . $row["product_name"] . "</td>";
echo
"<td>" . $row["quantity_in_stock"] . "</td>";
echo
"</tr>";
}
echo
"</table>";
} else {
echo
"<h1>No products found with the specified minimum quantity in stock.</h1>";
}

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Form</title>
</head>

<body>
<h1>form</h1>
<form action="form.php" method="post">
<p>Minimum stock quantity: <input type="text" name="minimum" id="minimum"></p>
<p><input type="submit">
</form>

</body>
</html>
up
0
Anonymous
18 minutes ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Survey </title>
<link href="styles.css" rel="stylesheet">
<script>
// Function to validate the form inputs
function CheckForm(form) {
// Clear previous error messages
let errorMessages = document.getElementsByClassName('error-message');
for (let message of errorMessages) {
message.innerText = ''; // Clear the error message text
}

let valid = true; // Flag to track if the form is valid

// Phone number validation
let phone = form.phone.value;
let phonePattern = /^\(02\)\d{8}$/; // Pattern to match (02) followed by 8 digits
if (!phonePattern.test(phone)) {
valid = false; // Set valid flag to false if phone number doesn't match pattern
document.getElementById('phone-error').innerText = ' Phone number must start with (02) and followed by 8 digits.'; // Display error message
}

// Favourite destination validation
let destination = form.dest.value;
if (destination.trim() === "") {
valid = false; // Set valid flag to false if destination is empty
document.getElementById('dest-error').innerText = ' Favourite destination is required.'; // Display error message
}

// Preferred meal validation
let meal = form.meal.value;
if (meal === "") {
valid = false; // Set valid flag to false if no meal option is selected
document.getElementById('meal-error').innerText = ' Preferred meal type is required.'; // Display error message
}

return valid; // Return the valid flag, if true form will be submitted, if false it won't
}

// Add event listener to call CheckForm function on form submission
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('Q3form').onsubmit = function() {
return CheckForm(this); // Validate form inputs before submission
};
});
</script>
</head>

<body>
<h1> Survey</h1>
<form id="Q3form" method="get" action="www.example.com" >

<fieldset>
<legend> About You </legend>
<p>
<label for="first">First Name:</label>
<input type="text" id="first" name="first">
<label for="last">Family Name:</label>
<input type="text" id="last" name="last">
</p>
<p>
<label for="ffno">Number:</label>
<input type="text" id="ffno" name="ffno" placeholder="#########">
</p>
</fieldset>
<br>

<fieldset>
<legend> Your Contact Details </legend>
<p>
<label for="email">Email address:</label>
<input type="text" id="email" name="email" placeholder="username@domainname">
<label for="phone">Home Phone:</label>
<input type="text" id="phone" name="phone" placeholder="(##)########">
<span id="phone-error" class="error-message"></span> <!-- Placeholder for phone error message -->
</p>
</fieldset>
<br>

<fieldset>
<legend> Preferences </legend>
<p>
<label for="dest">Favourite Destination:</label>
<input type="text" id="dest" name="dest">
<span id="dest-error" class="error-message"></span> <!-- Placeholder for destination error message -->
</p>
<label for="meal">Preferred meal:</label>
<select id="meal" name="meal" size="1">
<option value=""> -- </option>
<option value="std"> Standard </option>
<option value="veg"> Vegetarian </option>
<option value="vegan"> Vegan </option>
<option value="gf"> Gluten-free </option>
<option value="fruit"> Fruitarian </option>
<option value="meat"> Meat-lover's - no vegetables </option>
<option value="vegemite"> Vegemite sandwich </option>
</select>
<span id="meal-error" class="error-message"></span> <!-- Placeholder for
up
0
Anonymous
18 minutes ago
<?php
// Database connection information
$servername = "localhost"; // The server name or IP address where the MySQL database is hosted
$username = "_admin"; // The username to connect to the MySQL database
$password = "_2001_"; // The password associated with the MySQL username
$dbname = "customer"; // The name of the MySQL database to connect to

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname); // Establish a new connection to the MySQL database

// Check connection
if ($conn->connect_error) {
die(
"Connection failed: " . $conn->connect_error); // If the connection fails, output an error message and terminate the script
}

// Get user inputs from the form and sanitize them
$customerID = $conn->real_escape_string($_POST['customerNum']); // Retrieve and sanitize the customerID from the form input to prevent SQL injection
$status = $conn->real_escape_string($_POST['shipped']); // Retrieve and sanitize the status from the form input to prevent SQL injection

// Build the SQL query based on user input
$sql = "SELECT p.orderID, p.orderDate, p.shippingDate, c.customerID, c.firstName, c.lastName, c.postcode
FROM purchase p
JOIN customer c ON p.customerID = c.customerID
WHERE p.customerID = '
$customerID'"; // Start building the SQL query to retrieve orders for the specified customer

// Add condition for shipped status based on user selection
if ($status === 'Y') {
$sql .= " AND p.shipped = 'Y'"; // Append condition to the SQL query if the user selected "Shipped"
} else if ($status === 'N') {
$sql .= " AND p.shipped = 'N'"; // Append condition to the SQL query if the user selected "Not-shipped"
}

// Order the results by orderDate in ascending order
$sql .= " ORDER BY p.orderDate ASC"; // Append an ORDER BY clause to the SQL query to sort the results by orderDate in ascending order

// Execute the query
$result = $conn->query($sql); // Execute the SQL query and store the result in the $result variable

// Check if any results were returned
if ($result->num_rows > 0) {
// If there are results, display them in a table
echo "<table border='1'>"; // Start the HTML table and set the border attribute
echo "<tr><th>Order ID</th><th>Order Date</th><th>Shipping Date</th><th>Customer ID</th><th>First Name</th><th>Last Name</th><th>Postcode</th></tr>"; // Output the table headers

// Fetch and display each row of the result set
while($row = $result->fetch_assoc()) { // Loop through each row in the result set
echo "<tr>"; // Start a new table row
echo "<td>" . $row['orderID'] . "</td>"; // Display the orderID in a table cell
echo "<td>" . $row['orderDate'] . "</td>"; // Display the orderDate in a table cell
echo "<td>" . $row['shippingDate'] . "</td>"; // Display the shippingDate in a table cell
echo "<td>" . $row['customerID'] . "</td>"; // Display the customerID in a table cell
echo "<td>" . $row['firstName'] . "</td>"; // Display the firstName in a table cell
echo "<td>" . $row['lastName'] . "</td>"; // Display the lastName in a table cell
echo "<td>" . $row['postcode'] . "</td>"; // Display the postcode in a table cell
echo "</tr>"; // End the table row
}

echo
"</table>"; // End the HTML table
} else {
// If there are no results, display a message
echo "No orders were found that match your criteria."; // Output a message indicating that no orders were found
}

// Close the database connection
$conn->close(); // Close the connection to the MySQL database
?>
up
0
Anonymous
19 minutes ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title> <!-- The title for the webpage -->
</head>
<body>
<h1>H1 Heading</h1> <!-- Level 1 heading -->
<img src="image" alt="web"> <!-- Image with alt attribute -->
<p>Your text from here</p> <!-- Paragraph for the main content -->
<h2>Heading Question</h2> <!-- Level 2 heading -->
<ol> <!-- Ordered list -->
<li>Benefit 1</li>
<li>Benefit 2</li>
<li>Benefit 3</li>
</ol>
<p><a href=""></a></p> <!-- Hyperlink -->
</body>
</html>

h1 {
font-size: 1.5em;
}

body {
background-color: lightblue; the page
border: 2px solid red;
}

img {
width: 200px;
height: 200px;
}

h1, img {
text-align: center;
float: right;
}

p, ol {
text-align: left;
padding-left: 20px;
}

a {
text-align: center;
font-family: 'Times New Roman', Times, serif;
}
up
0
Anonymous
20 minutes ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup Form</title> <!-- The title for the webpage -->
<style>
.error {
color: red;
font-size: 0.9em;
}
.error-border {
border: 2px solid red;
}
</style>
<script>
function CheckForm() {
var form = document.forms["signup"];
var password = form["password"].value;
var checkboxes = form["checkbox"];
var firstName = form["firstname"].value;
var lastName = form["lastname"].value;
var radios = form["radio"];
var valid = true;

// Validate password length
if (password.length < 6) {
document.getElementById("password_error").innerHTML = "Password must be at least 6 characters long.";
document.getElementById("password").classList.add("error-border");
valid = false;
} else {
document.getElementById("password_error").innerHTML = "";
document.getElementById("password").classList.remove("error-border");
}

// Validate at least one checkbox is checked
var checkboxChecked = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkboxChecked = true;
break;
}
}
if (!checkboxChecked) {
document.getElementById("checkbox_error").innerHTML = "At least one checkbox must be checked.";
valid = false;
} else {
document.getElementById("checkbox_error").innerHTML = "";
}
// Validate first name is not empty
if (firstName.trim() === "") {
document.getElementById("firstname_error").innerHTML = "First name is required.";
document.getElementById("firstname").classList.add("error-border");
valid = false;
} else {
document.getElementById("firstname_error").innerHTML = "";
document.getElementById("firstname").classList.remove("error-border");
}
// Validate last name is not empty
if (lastName.trim() === "") {
document.getElementById("lastname_error").innerHTML = "Last name is required.";
document.getElementById("lastname").classList.add("error-border");
valid = false;
} else {
document.getElementById("lastname_error").innerHTML = "";
document.getElementById("lastname").classList.remove("error-border");
}
// Validate one radio button is selected
var radioChecked = false;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
radioChecked = true;
break;
}
}
if (!radioChecked) {
document.getElementById("radio_error").innerHTML = "Please select one option.";
valid = false;
} else {
document.getElementById("radio_error").innerHTML = "";
}
return valid;
}
</script>
</head>
<body>
<form name="signup" onsubmit="return CheckForm()">
<label for="firstname">First Name:</label>
<input type="text" id="firstname" name="firstname">
<span id="firstname_error" class="error"></span><br>
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lastname">
<span id="lastname_error" class="error"></span><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<span id="password_error" class="error"></span><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
up
0
Anonymous
20 minutes ago
<?php
$servername
= "localhost";
$username = "root";
$password = "";
$dbname = "name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die(
"Connection failed: " . $conn->connect_error);
}

$customerid = $_POST['customerid']; // Retrieve customer ID from form submission

// SQL query to select customer information
$sql = "SELECT customerID, FIRSTNAME, LASTNAME, GENDER, CASH FROM CUSTOMER WHERE customerID = '$customerid'";
$result = $conn->query($sql);

if (
$result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo
"customerID: " . $row["CustomerID"]. " - Name: " . $row["FIRSTNAME"]. " " . $row["LASTNAME"]. " - Gender: " . $row["GENDER"]. " - CASH: " . $row["CASH"]. "<br>";
}
} else {
echo
"No customer found with customerID: $customerid";
}
$conn->close();
?>
up
0
Anonymous
21 minutes ago
<?php
$servername
= "localhost";
$username = "root";
$password = "";
$dbname = "";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die(
"Connection failed: " . $conn->connect_error);
}

if (
$_SERVER["REQUEST_METHOD"] == "POST") {
$marketid = $_POST['marketid']; // Retrieve course ID from form submission

// SQL query to select student IDs for the given course ID
$sql = "SELECT customerID FROM ENROLMENT WHERE marketID = '$marketid'";
$result = $conn->query($sql);

if (
$result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo
"customerID: " . $row["customerID"]. "<br>";
}
} else {
echo
"No students found for marketID: $courseid";
}

// Display the form again with the course ID
echo '<form method="post" action="Q.php">
<input type="text" name="marketid" value="'
.$marketid.'">
<input type="submit" value="Submit">
</form>'
;
} else {
// Display the form for the first time
echo '<form method="post" action="Q.php">
<input type="text" name="marketid">
<input type="submit" value="Submit">
</form>'
;
}
$conn->close();
?>
up
0
Anonymous
22 minutes ago
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form Validation</title>
<style>
.error {
color: red;
font-size: 12px;
}

.error-input {
border: 2px solid red;
}
</style>
</head>
<body>

<h2>Form Validation</h2>

<form id="myForm" onsubmit="return validateForm()">
<label for="fname">First name: </label>
<input type="text" id="fname" name="fname"><span id="fnameErr" class="error"></span><br><br>

<label for="lname">Last name: </label>
<input type="text" id="lname" name="lname"><span id="lnameErr" class="error"></span><br><br>

<label>Password: </label>
<input type="password" id="password" name="password"><span id="passwordErr" class="error"></span><br><br>

<label for="male">Male</label>
<input type="radio" id="male" name="gender">
<label for="female">Female</label>
<input type="radio" id="female" name="gender">
<span id="genderErr" class="error"></span><br><br>

<input type="checkbox" id="checkbox1" name="checkbox1">
<label for="checkbox1">Option 1</label>
<input type="checkbox" id="checkbox2" name="checkbox2">
<label for="checkbox2">Option 2</label>
<span id="checkboxErr" class="error"></span><br><br>

<input type="submit" value="Submit">
</form>

<script>
function validateForm() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var password = document.getElementById("password").value;
var gender = document.querySelector('input[name="gender"]:checked');
var checkbox1 = document.getElementById("checkbox1").checked;
var checkbox2 = document.getElementById("checkbox2").checked;
var valid = true;

document.getElementById("fnameErr").innerHTML = "";
document.getElementById("lnameErr").innerHTML = "";
document.getElementById("passwordErr").innerHTML = "";
document.getElementById("genderErr").innerHTML = "";
document.getElementById("checkboxErr").innerHTML = "";

if (fname == "") {
document.getElementById("fnameErr").innerHTML = "First name is required";
document.getElementById("fname").classList.add("error-input");
valid = false;
} else {
document.getElementById("fname").classList.remove("error-input");
}

if (lname == "") {
document.getElementById("lnameErr").innerHTML = "Last name is required";
document.getElementById("lname").classList.add("error-input");
valid = false;
} else {
document.getElementById("lname").classList.remove("error-input");
}

if (password.length < 6) {
document.getElementById("passwordErr").innerHTML = "Password must be at least 6 characters long";
document.getElementById("password").classList.add("error-input");
valid = false;
} else {
document.getElementById("password").classList.remove("error-input");
}

if (!gender) {
document.getElementById("genderErr").innerHTML = "Gender selection is required";
valid = false;
}

if (!checkbox1 && !checkbox2) {
document.getElementById("checkboxErr").innerHTML = "At least one checkbox must be checked";
valid = false;
}

return valid;
}
</script>

</body>
</html>
up
0
Anonymous
23 minutes ago
<?php

$servername
= "your_server_name";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

if (
$conn->connect_error) {
die(
"Connection failed: " . $conn->connect_error);
}

$errors = array();

if (
$_SERVER["REQUEST_METHOD"] == "POST") {
$courseid = $_POST['courseid'];
$studentid = $_POST['studentid'];

$courseid_valid = true;
if (!
ctype_alnum($courseid) || strlen($courseid) > 7) {
$errors[] = "Invalid COURSEID: must be at most 7 characters.";
$courseid_valid = false;
}

$studentid_valid = true;
if (!
is_numeric($studentid) || strlen($studentid) != 8 || ($studentid[0] != '4' && $studentid[0] != '5')) {
$errors[] = ": must be an 8-digit number starting with .";
$studentid_valid = false;
}

if (
$courseid_valid && $studentid_valid) {
echo
"Student successfully.";
} else {
foreach (
$errors as $error) {
echo
$error . "<br>";
}
}

// echo 'bra href="qqq"Return</a>';
}

$conn->close();
?>
up
1
chris at ocproducts dot com
7 years ago
Guide to script parameters...

Data: $_GET
Data type: Array (map)
Purpose: Contains all GET parameters (i.e. a parsed URL query string).
Caveat: GET parameter names have to be compliant with PHP variable naming, e.g. dots are not allowed and get substituted.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['QUERY_STRING']
Data type: String
Purpose: Gets an unparsed URL query string.
Caveat: Not set on all PHP environments, may need setting via http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['argv']
Data type: Array (list)
Purpose: Get CLI call parameters.
Works on web mode: Tenuous (just contains a single parameter, the query string)
Works on CLI mode: Yes
up
3
silverquick at gmail dot com
15 years ago
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond
up
3
pudding06 at gmail dot com
15 years ago
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>

This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
up
0
lilJoshu
5 years ago
Remember,

Although $_SERVER["REQUEST_METHOD"] is initially built with GET, POST, PUT, HEAD in mind, a server can allow more.

This may be important if you're building a RESTful interfaces that will also use methods such as PATCH and DELETE.

Also important as a security risk as a possible point of injection. In the event of building something acting based on REQUEST_METHOD, it's recommended to put it in a switch statement.

<?php
switch ($_SERVER["REQUEST_METHOD"]){
case
"PUT":
foo_replace_data();
break;
case
"POST":
foo_add_data();
break;
case
"HEAD";
foo_set_that_cookie();
break;
case
"GET":
default:
foo_fetch_stuff()
break;
}

?>
up
1
picov at e-link dot it
12 years ago
A simple function to detect if the current page address was rewritten by mod_rewrite:

<?php
public function urlWasRewritten() {
$realScriptName=$_SERVER['SCRIPT_NAME'];
$virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
return !(
$realScriptName==$virtualScriptName);
}
?>
up
1
wbeaumo1 at gmail dot com
13 years ago
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
up
-1
sammyhacker at gmail dot com
2 years ago
To put it simply, $_SERVER contains all the environment variables.

CGI works by an HTTP application server filling in all the required environment variables and invoking the PHP process. And these environment variables are stored under $_SERVER.
up
-1
jit_chavan at yahoo dot com
10 years ago
searched $_SERVER["REDIRECT_URL"] for a while and noted that it is not mentioned in php documentation page itself. look like this is only generated by apache server(not others) and using $_SERVER["REQUEST_URI"] will be useful in some cases as mine.
up
-2
plugwash at p10link dot net
9 years ago
Be aware that it's a bad idea to access x-forwarded-for and similar headers through this array. The header names are mangled when populating the array and this mangling can introduce spoofing vulnerabilities.

See http://en.wikipedia.org/wiki/User:Brion_VIBBER/Cool_Cat_incident_report for details of a real world exploit of this.
up
-4
2962051004 at qq dot com
6 years ago
<?php
/*
Sometimes you will find that your website will not get the correct user IP after adding CDN, then this function will help you
*/
function real_ip()
{
$ip = $_SERVER['REMOTE_ADDR'];
if (isset(
$_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
foreach (
$matches[0] AS $xip) {
if (!
preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
$ip = $xip;
break;
}
}
} elseif (isset(
$_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset(
$_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif (isset(
$_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
$ip = $_SERVER['HTTP_X_REAL_IP'];
}
return
$ip;

}
echo
real_ip();

?>
up
-1
kamil00110
10 months ago
This code can be used to help find somone that tries to dig throught the server files to find something.

.htaccess

ErrorDocument 404 /your.php
ErrorDocument 403 /your.php

<?php
//get time
$time = date("H:i:s d.m.y");
//get user address
$usr = $_SERVER['REMOTE_ADDR'];
//get entered url of the "visitor"
$url = $_SERVER['REQUEST_URI'];
//get your servers address
$ip = $_SERVER['SERVER_ADDR'];
//put toogether
$sus = "[".$time."] ".$usr." ".$ip.$url.PHP_EOL;
//write an log file
file_put_contents("susip.txt", $sus, FILE_APPEND);
?>
up
-3
Johan Winge
4 years ago
It should probably be noted that the value of $_SERVER['SERVER_PROTOCOL'] will never contain the substring "HTTPS". Assuming this is a common source of bugs and confusion. Instead, see $_SERVER['HTTPS'].
up
-5
cupy at email dot cz
14 years ago
Tech note:
$_SERVER['argc'] and $_SERVER['argv'][] has some funny behaviour,
used from linux (bash) commandline, when called like
"php ./script_name.php 0x020B"
there is everything correct, but
"./script_name.php 0x020B"
is not correct - "0" is passed instead of "0x020B" as $_SERVER['argv'][1] - see the script below.
Looks like the parameter is not passed well from bash to PHP.
(but, inspected on the level of bash, 0x020B is understood well as $1)

try this example:

------------->8------------------
cat ./script_name.php
#! /usr/bin/php

if( $_SERVER['argc'] == 2)
{
// funny... we have to do this trick to pass e.g. 0x020B from parameters
// ignore this: "PHP Notice: Undefined offset: 2 in ..."
$EID = $_SERVER['argv'][1] + $_SERVER['argv'][2] + $_SERVER['argv'][3];
}
else
{ // default
$EID = 0x0210; // PPS failure
}
up
-5
DanielTahar
4 years ago
To expand a bit on the price you could pay for relying on 'HTTP_REFERER': several large news sites I read often have paywalls, with cookies in place so you can only read X articles before you must subscribe; if using Incognito, they count the number of times you accessed via the same IP; everything to get you to subscribe. However, in order to be appealing, any visit where the 'HTTP_REFERER' is Google News will give you the entire article. I'm sure it's a dilemma their webmasters have, but for now any time someone sends you a story on one of them, all you have to do is search for the title and click the result from Google News. Bottom line: never count on it.

PS (1): ofcourse i'm talking about a friend. I pay for content.
PS (2): after some debate, the RFC decided to keep 'HTTP_REFERER', although it's misspelled.
up
-4
Florin C
1 year ago
<?php
//Working example tested with success in Debian Linux with Apache 2.4

$protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http'; //thanks to Mark Simon @ https://www.php.net/manual/en/reserved.variables.server.php
$doc_root = $_SERVER['DOCUMENT_ROOT']; // e.g. /var/www/webabc/web/
$module_path = dirname(__FILE__); // e.g. /var/www/webabc/web/modules/verstion152/
$host = $_SERVER['HTTP_HOST']; // e.g. 192.168.1.4

$online_path = $protocol .'://'. $host . '/' . str_replace($doc_root, '', $module_path);

echo
"The online path is: " . $online_path;
To Top