|
 |
Since PHP 4.1.0, the preferred method for retrieving
external variables is
with the superglobals mentioned below. Before this time, people relied
on either register_globals
or the long predefined PHP arrays ($HTTP_*_VARS).
Начиная с PHP 5.0.0, длинные
предопределенные переменные
массивов PHP могут быть отключены директивой
register_long_arrays.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_SERVER_VARS.
$_SERVER is an array containing information
such as headers, paths, and script locations. The entries in this
array are created by the webserver. There is no guarantee that
every webserver will provide any of these; servers may omit some,
or provide others not listed here. That said, a large number of
these variables are accounted for in the CGI 1.1 specification, so you should
be able to expect those.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_SERVER; to access it within functions or methods, as
you do with $HTTP_SERVER_VARS.
$HTTP_SERVER_VARS contains the same initial
information, but is not an autoglobal. (Note that
$HTTP_SERVER_VARS and $_SERVER
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_SERVER and $HTTP_SERVER_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
You may or may not find any of the following elements in
$_SERVER. Note that few, if any, of these will be available (or
indeed have any meaning) if running PHP on the command line.
- '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/test.php/foo.bar
would be /test.php/foo.bar.
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 since PHP 4.3.0. Previously it was not available.
- '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;
i.e. 'CGI/1.1'.
- '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.
- '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; i.e. 'HTTP/1.0';
- 'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET',
'HEAD', 'POST', 'PUT'.
Замечание:
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. Available since PHP 5.1.0.
- '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.
- 'HTTP_ACCEPT'
Contents of the Accept: header from the
current request, if there is one.
- 'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header
from the current request, if there is one. Example:
'iso-8859-1,*,utf-8'.
- 'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header
from the current request, if there is one. Example: 'gzip'.
- 'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header
from the current request, if there is one. Example: 'en'.
- 'HTTP_CONNECTION'
Contents of the Connection: header from
the current request, if there is one. Example: 'Keep-Alive'.
- 'HTTP_HOST'
Contents of the Host: header from the
current request, if there is one.
- 'HTTP_REFERER'
The address of the page (if any) which referred the user
agent to the current page. This is set by the user agent. Not
all user agents will set this, and some provide the ability
to modify HTTP_REFERER as a feature. In
short, it cannot really be trusted.
- 'HTTP_USER_AGENT'
Contents of the User-Agent: header from
the current request, if there is one. This is a string
denoting the user agent being which is accessing the page. A
typical example is: Mozilla/4.5 [en] (X11; U;
Linux 2.2.9 i586). Among other things, you
can use this value with get_browser() to
tailor your page's output to the capabilities of the user
agent.
- '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 off the
REMOTE_ADDR of the user.
Замечание:
Your web server must be configured to create this variable. For
example in Apache you'll need HostnameLookups On
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.
- 'SCRIPT_FILENAME'
The absolute pathname of the currently executing script.
Замечание:
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.
- '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.
Замечание:
As of PHP 4.3.2, PATH_TRANSLATED is no longer set
implicitly under the Apache 2 SAPI in contrast
to the situation in Apache 1, where it's set to the same value as
the SCRIPT_FILENAME server variable when it's not
populated by Apache. This change was made to comply with the
CGI specification that
PATH_TRANSLATED should only exist if
PATH_INFO is defined.
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 running under Apache as module 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 running under Apache or IIS (ISAPI on PHP 5) as module doing
HTTP authentication this variable is set to the username provided by
the user.
- 'PHP_AUTH_PW'
When running under Apache or IIS (ISAPI on PHP 5) as module doing
HTTP authentication this variable is set to the password provided by
the user.
- 'AUTH_TYPE'
When running under Apache as module doing HTTP authenticated this
variable is set to the authentication type.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_ENV_VARS.
These variables are imported into PHP's global namespace from the
environment under which the PHP parser is running. Many are
provided by the shell under which PHP is running and different
systems are likely running different kinds of shells, a
definitive list is impossible. Please see your shell's
documentation for a list of defined environment variables.
Other environment variables include the CGI variables, placed
there regardless of whether PHP is running as a server module or
CGI processor.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_ENV; to access it within functions or methods, as
you do with $HTTP_ENV_VARS.
$HTTP_ENV_VARS contains the same initial
information, but is not an autoglobal. (Note that
$HTTP_ENV_VARS and $_ENV
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_ENV and $HTTP_ENV_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_COOKIE_VARS.
An associative array of variables passed to the current script
via HTTP cookies. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_COOKIE; to access it within functions or methods, as
you do with $HTTP_COOKIE_VARS.
$HTTP_COOKIE_VARS contains the same initial
information, but is not an autoglobal. (Note that
$HTTP_COOKIE_VARS and $_COOKIE
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_COOKIE and $HTTP_COOKIE_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_GET_VARS.
An associative array of variables passed to the current script
via the HTTP GET method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_GET; to access it within functions or methods, as
you do with $HTTP_GET_VARS.
$HTTP_GET_VARS contains the same initial
information, but is not an autoglobal. (Note that
$HTTP_GET_VARS and $_GET
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_GET and $HTTP_GET_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_POST_VARS.
An associative array of variables passed to the current script
via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_POST; to access it within functions or methods, as
you do with $HTTP_POST_VARS.
$HTTP_POST_VARS contains the same initial
information, but is not an autoglobal. (Note that
$HTTP_POST_VARS and $_POST
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_POST and $HTTP_POST_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_POST_FILES.
An associative array of items uploaded to the current script
via the HTTP POST method. Automatically global in any scope.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_FILES; to access it within functions or methods, as
you do with $HTTP_POST_FILES.
$HTTP_POST_FILES contains the same
information, but is not an autoglobal. (Note that
$HTTP_POST_FILES and $_FILES
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_FILES and $HTTP_POST_FILES
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. There is no equivalent array in earlier
versions.
Замечание:
Prior to PHP 4.3.0, $_FILES information was
also included in $_REQUEST.
An associative array consisting of the contents of
$_GET, $_POST,
and $_COOKIE.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_REQUEST; to access it within functions or methods.
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_REQUEST array. For related information, see
the security chapter titled Using Register
Globals. These individual globals are not autoglobals.
Замечание:
Introduced in 4.1.0. In earlier versions, use
$HTTP_SESSION_VARS.
An associative array containing session variables available to
the current script. See the Session
functions documentation for more information on how this
is used.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$_SESSION; to access it within functions or methods, as
you do with $HTTP_SESSION_VARS.
$HTTP_SESSION_VARS contains the same
information, but is not an autoglobal. (Note that
$HTTP_SESSION_VARS and $_SESSION
are different variables and that PHP handles them as such)
If the register_globals directive
is set, then these variables will also be made available in the
global scope of the script; i.e., separate from the
$_SESSION and $HTTP_SESSION_VARS
arrays. For related information, see the security chapter titled
Using Register
Globals. These individual globals are not autoglobals.
Замечание:
$GLOBALS has been available since PHP 3.0.0.
An associative array containing references to all variables which
are currently defined in the global scope of the script. The
variable names are the keys of the array.
This is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a
script. You don't need to do a global
$GLOBALS; to access it within functions or methods.
$php_errormsg is a variable containing the
text of the last error message generated by PHP. This variable
will only be available within the scope in which the error
occurred, and only if the track_errors configuration
option is turned on (it defaults to off).
Predefined Variables
jwl007
10-May-2006 12:36
Here's a quick function for replacing values within a query string. I use this quite a bit for ordering a list obtained from a database.
e.g.
If I want a link to order the list by firstname, I would use:
<a href=".replaceQueryString('orderby',$firstname).">first</a>.
If I want a link to order by last name, I would use:
<a href=".replaceQueryString('orderby',$lastname).">last</a>.
//$var = global query variable
//$val = new value for global query variable
function replaceQueryString($var,$val){
global $HTTP_SERVER_VARS;
$query_string = $HTTP_SERVER_VARS["QUERY_STRING"];
return preg_replace("/$var=[\\d\\w]*/","$var=$val",$query_string);
}
Hope this helps someone..
tchamp
26-Apr-2006 07:24
Be careful with HTTP_HOST behind a proxy server. Use these instead.
[HTTP_X_FORWARDED_FOR]
[HTTP_X_FORWARDED_HOST]
[HTTP_X_FORWARDED_SERVER]
In my situation, I used [HTTP_X_FORWARDED_SERVER] in place of [HTTP_HOST] in order get the machine and hostname (www.myurl.com)
Ben XO
14-Apr-2006 06:18
So you have an application in your web space, with a URL such as this:
http://<host>/<installation_path>/
and pages such as
http://<host>/<installation_path>/subfolder1/subfolder2/page.php
You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).
How to work out <installation_path> without hard-coding it into a config file?
<?php
$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); $_REAL_BASE_DIR = realpath(dirname(__FILE__)); $_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); $INSTALLATION_PATH = $_MY_PATH_PART
? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
: dirname($_SERVER['SCRIPT_NAME'])
; ?>
todd dot kisov at yahoo dot com
03-Apr-2006 02:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:
function JavaScript_Unicode_URL_2_Str($js_uni_str) {
$res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
$res = str_replace('"', '\"', $res); // if in str "
$res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
$res = $res[0];
$res = iconv('UTF-8', ini_get('default_charset'), $res);
return $res;
}
31-Mar-2006 09:56
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"]. I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):
<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
$_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
$_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
mjs at beebo dot org
30-Mar-2006 01:24
Note that PHP_SELF will not be equal to REQUEST_URI under Apache if mod_rewrite has been used to move one URL to another--PHP_SELF will contain the rewritten address, and REQUEST_URI will contain the URL the user sees in their browser.
kumazatheef
17-Mar-2006 10:53
Just to clarify the " Prior to PHP 4.3.0, $_FILES information was also included in $_REQUEST." item ...
despite the fact that a file upload form item looks & kinda acts like a text item, does not mean the value will be placed in $_REQUEST ... so, you can type in the path into the text item (except Safari and a few others), but the name/value is only in $_FILES ... no trace of it is in $_REQUEST ...
Makes sense and yet not quite at the same time.
adam3000 at gmail dot com
15-Mar-2006 10:30
I was trying to find an alternative to $_SERVER['REQUEST_URI'] for a Windows NT set up and the ones below didn't really work for me so here's my solution using eustf at hotmail dot com's suggestion of $_SERVER['PHP_SELF']:
// if 'REQUEST_URI' isn't available then ...
if(!isset($_SERVER['REQUEST_URI'])) {
// ... set my own request url and ...
$temp_request_url = $_SERVER['PHP_SELF'];
// ... test for and add url variables to my request url ...
if (isset($HTTP_SERVER_VARS['QUERY_STRING'])) {
$temp_request_url .= (strpos($updateGoTo, '?')) ? "&" : "?";
$temp_request_url .= $HTTP_SERVER_VARS['QUERY_STRING'];
}
} else {
// ... otherwise use the regular 'REQUEST_URI'
$temp_request_url = $_SERVER['REQUEST_URI'];
}
Aardvark
07-Mar-2006 01:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained using a function such as:
function getQueryParameter ($strParam) {
$aParamList = explode('&', $_SERVER['QUERY_STRING']);
$i = 0;
while ($i < count($aParamList)) {
$aParam = split('=', $aParamList[$i]);
if ($strParam == $aParam[0]) {
return $aParam[1];
}
}
return "";
}
or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
justin dot (nospam)george at gmail dot com
28-Feb-2006 12:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim($_SERVER['PHP_SELF'], "/\\");
$GLOBALS['SITE_ROOT'] = "http://$host$uri";
while ($i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>
While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea
(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
nathan
22-Feb-2006 08:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate. If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas.
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's... It's a nice idea, but as the example code shows, it should only be used to set defaults.
ticklemeozmo at gmail dot com
14-Feb-2006 09:44
Using a combination of magic and a few examples from below (thank you to those below), the following two functions should provide the script with a list (in order) of what is after the script.
printvars.php:
<?php
function array_compress($array) {
$aReturn = array();
foreach ($array as $value)
if (strlen($value) > 0) { $aReturn[] = $value; }
return $aReturn;
}
function getPathVariables() {
$sPathPS = $_SERVER[PHP_SELF];
$sPathFS = __FILE__;
$aPathPS = array_reverse(explode("/", $sPathPS));
$aPathFS = array_reverse(explode("/", $sPathFS));
$aReturn = array();
$x = 0;
while ( $aPathPS[$x] != $aPathFS[$x] && $aPathPS[$x] != $aPathFS[0] ) {
array_unshift($aReturn, $aPathPS[$x]) ;
$x++;
}
return $aReturn;
}
print_r(array_compress(getPathVariables()));
?>
----
Calling: http://www.website.com/temp/printvars.php/or/whatever/something.jpg
returns:
Array (
[0] => or
[1] => whatever
[2] => something.jpg
)
geza at turigeza dot com
11-Feb-2006 05:13
Above the manual says
'$_REQUEST is an associative array consisting of the contents of $_GET, $_POST, and $_COOKIE.'
However
$_REQUEST doesn't always contain the same elements as
$_GET+$_POST+$_REQUEST;
Basically if you add an element to the $_POST array that element does not automatically get added to REQUEST as well. It's easy to understand why :)
<?php
$_POST['geza'] = 'geza';
$_GET['bela'] = 'bela';
echo '<pre>';
print_r($_POST);
print_r($_GET);
print_r($_REQUEST);
echo '</pre>';
?>
will output this
Array
(
[geza] => geza
)
Array
(
[bela] => bela
)
Array
(
)
nospam at joot dot com
10-Feb-2006 03:02
[Editor's note: As much as you may hate us lazy programmers, we highly recommend the use of DOM (http://php.net/dom) or SimpleXML (http://php.net/simplexml) for handling XML data. It's much, much, much, much safer than your method. :)]
Man, I hate lazy programmers. Let's have no more excuses for requiring your viewers to fill in their City and Country, okay?
PART ONE - The Lookup
$ip = get_remote_ip();
$location = http_get( "http://api.hostip.info/?ip=$ip" );
$contents = get_tag_contents( $location, "Hostip" );
$city = trim( get_tag_contents( $contents, "gml:name" ) );
$country = trim( get_tag_contents( $contents, "countryAbbrev" ) );
if( stristr( $city, "private" ) ) {
$city = "";
}
if( stristr( $country, "xx" ) ) {
$country = "US";
}
PART TWO - The Functions
function get_remote_ip() {
return $_SERVER['REMOTE_ADDR'];
}
function http_get( $url ) {
$request = fopen( $url, "rb" );
$result = "";
while( !feof( $request ) ) {
$result .= fread( $request, 8192 );
}
fclose( $request );
return $result;
}
function get_tag_contents( $xml, $tag ) {
$result = "";
$s_tag = "<$tag>";
$s_offs = strpos( $xml, $s_tag );
// If we found a starting offset, then look for the end-tag.
//
if( $s_offs ) {
$e_tag = "</$tag>";
$e_offs = strpos( $xml, $e_tag, $s_offs );
// If we have both tags, then dig out the contents.
//
if( $e_offs ) {
$result = substr(
$xml,
$s_offs + strlen( $s_tag ),
$e_offs - $s_offs - strlen( $e_tag ) + 1 );
}
}
return $result;
}
PART THREE - The HTML Form
<input type="text" name="city" id="city" value="<? echo $city; ?>" size="40" maxlength="50" />
<option value="AU" <? if( $country == "AU" ) echo "SELECTED='true'" ?>>Australia</option>
<option value="CA" <? if( $country == "CA" ) echo "SELECTED='true'" ?>>Canada</option>
<option value="GB" <? if( $country == "GB" ) echo "SELECTED='true'" ?>>United Kingdom</option>
<option value="US" <? if( $country == "US" ) echo "SELECTED='true'" ?>>United States</option>
etc.
Gerry
25-Jan-2006 05:14
In relation to Mr. Obvious' comment concerning using apache_request_headers() to get a more reliable referer. I don't believe this works as both it and PHP would be retrieving the information from the 'referer' header. All you would be doing by using apache_request_headers() is giving yourself more work.
Some test code which shows that both are identical:
<?php
$host=apache_request_headers();
echo "\$host['Referer'] = {$host['Referer']}\n";
echo "\$_SERVER['HTTP_REFERER'] = {$_SERVER['HTTP_REFERER']}\n";
?>
You can edit the referer using a tool such as the LiveHTTPHeaders extension for Firefox.
If there was a more accurate way of determining the referer, then PHP would most likely be doing it.
de dot php dot net at derdickehase dot de
23-Jan-2006 12:05
There's one key sentence about $_SESSION:
... Therefore, you do not need to use the global keyword for $_SESSION ...
In PHP 4.3.4 you better don't import $_SESSION within any function with
"global", otherwise your $_SESSION array will be overwritten and all
information of it will be lost.
---
... Sie brauchen dieses Array nicht mit global $_SESSION; in
Funktionen oder Methoden importieren ...
In PHP 4.3.4 sollte man lieber nirgendwo(!) in irgendwelchen Funktionen
mit "global" das Array $_SESSION importieren, denn dann wird das alte
Array berschrieben und alle Session-Informationen gehen verloren.
marsh at NOSPAM-TAKETHATSPAMMER dot uri
19-Jan-2006 08:05
The solution advanced by info at meshkaat dot com does not work correctly on machines with IIS configured to use
a virtual directory as the launch point. The address strings for $_SERVER['SCRIPT_FILENAME'] and $_SERVER['PHP_SELF'] will not necessarily have the same name for the highest level directory in $_SERVER['PHP_SELF'], and therefore this solution will not return the proper value.
marsh at NOSPAM-TAKETHATSPAMMER dot uri dot edu
11-Jan-2006 07:57
Under Windows XP SP2 and IIS, $_SERVER('x') returns a path using forward slash '/' as the separator, where x is:
PHP_SELF, SCRIPT_NAME
These arguments, however, all return a path using backward slash, '\' as the separator:
__FILE__, SCRIPT_FILENAME, and DOCUMENT_ROOT (if you use one of the methods mentioned previously).
Also note that if the name of the last directory in the document root includes a space, the methods described above for setting DOCUMENT_ROOT will return a value that drops the everything past the space.
Andy Staudacher, gmx.ch add ast before @
20-Dec-2005 05:02
The following code is licensed under the GPL and it is from the gallery.menalto.com project.
<?php
function fixCookieVars($force=false, $unset=false)
?>
The source code can be found at:
http://cvs.sourceforge.net/viewcvs.py/gallery/gallery2/
modules/core/classes/GalleryUtilities.class?rev=1.146&view=markup
Mr. Obvious
14-Dec-2005 11:37
HTTP_REFERER Replacement
Being that REFERER is not a reliable resource to determine if a user is visiting a link from your domain, try using apache_request_headers() instead (formerly getallheaders). I found this to work very well with both IE and Netscape/FireFox when determining if a user is downloading a file from outside of my domain.
<?php
$host=apache_request_headers();
if(!eregi('domain.com',$host[Referer])){
}else{
}
?>
info at meshkaat dot com
06-Dec-2005 05:03
How to get $_SERVER["DOCUMENT_ROOT"] on IIS :
if(!isset($_SERVER["DOCUMENT_ROOT"]))
{$_SERVER["DOCUMENT_ROOT"]=substr($_SERVER['SCRIPT_FILENAME'] , 0 , -strlen($_SERVER['PHP_SELF'])+1 );
}
it simply works!
chris at vault5 dot com
30-Nov-2005 07:17
Since $_SERVER['DOCUMENT_ROOT'] is not always present, the following will provide it where $_SERVER dosen't.
<?php
function resolveDocumentRoot() {
$current_script = dirname($_SERVER['SCRIPT_NAME']);
$current_path = dirname($_SERVER['SCRIPT_FILENAME']);
$adjust = explode("/", $current_script);
$adjust = count($adjust)-1;
$traverse = str_repeat("../", $adjust);
$adjusted_path = sprintf("%s/%s", $current_path, $traverse);
return realpath($adjusted_path);
}
?>
It counts the number of folders down the path we are in the URL, then moves that number of folders up the current path... end result should be the document root :)
It wont work with virtual folders or in any situation where the folder in the URL dosen't map to a real folder on the disk (like when using rewrites).
webmaster at neosign dot net
08-Nov-2005 07:42
this is for finding Document root in IIS.
it's like $_SERVER["DOCUMENT_ROOT"]
if(!isset($_SERVER["DOCUMENT_ROOT"])){
$_SERVER["DOCUMENT_ROOT"]=$str_replace('\\','/',getcwd());
}
it's work!!
by
webmaster@neosign.net
lorenpr at gmail dot com
01-Nov-2005 03:04
Here's a simple function that has proven reliable for me in checking if a user has refreshed the current page on a website.
function pageRefreshed()
{
if($_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0')
return true;
return false;
}
webmaster at eclipse dot org
11-Oct-2005 08:01
In response to tobias at net-clipping dot de
It is not an Apache bug. Please read http://httpd.apache.org/docs/2.1/mod/core.html#errordocument carefully (2.1 version here, 2.0 and 1.x is similar).
In short, if your ErrorDocument start with http:// Apache sends a redirect (302) to the error document, hence losing your original referer. If your ErrorDocument points to a relative path, 404 is maintained and so are your variables.
From the Apache manual:
"Note that when you specify an ErrorDocument that points to a remote URL (ie. anything with a method such as http in front of it), Apache will send a redirect to the client to tell it where to find the document, even if the document ends up being on the same server. This has several implications, the most important being that the client will not receive the original error status code, but instead will receive a redirect status code. This in turn can confuse web robots and other clients which try to determine if a URL is valid using the status code. In addition, if you use a remote URL in an ErrorDocument 401, the client will not know to prompt the user for a password since it will not receive the 401 status code. Therefore, if you use an ErrorDocument 401 directive then it must refer to a local document."
D.
webadmin at wibn dot net
05-Oct-2005 02:55
I like using the $_REQUEST variable because my scripts work as expected regardless of request method and I can set per-user default values with cookies or session variables.
I was having problems because $_REQUEST was preferring cookie-method values over GET- and POST-method values. I have no access to php.ini on my hosted web page and, of course, ini_set("variables_order","ESCGP"); has no effect because $_REQUEST is created before my script starts.
The following script fixed my problem:
foreach (array("_GET","_POST") as $source) {
foreach (${$source} as $idx => $value) {
$_REQUEST[$idx]=$value;
};
};
unset($source,$idx,$value);
Simply fill the array() with the names of the arrays you want to load into $_REQUEST, in increasing order of preference.
drew dot griffiths at clare dot net
30-Sep-2005 08:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...
Whilst this is effective, a line in the .htaccess such as:
RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]
will throw the requested profile in a variable $profile to the showprofile.php page.
You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);
Hope this helps - Works well for me
Drew
jeromenelson at gmail dot com
19-Sep-2005 03:56
You can take advantage of 404 error to an usable redirection using REQUEST_URI ...
For example the following program can retrieve the information for the 'search_string', for a given URI: http://servername/profiles/search_string, even though there's no such path.
Do the following steps..
Step 1: Edit Apache config: set
ErrorDocument 404 "/missing.php"
Step 2: Write the missing.php as follows ...
<?
$mainPath = "/profiles/"; $mpLength = strlen( $mainPath );
$request_uri = $_SERVER['REQUEST_URI'];
if ( $mainPath != substr($request_uri,0,$mpLength) ) { echo "404 Page Not Found !";
exit();
}
$name = substr ($request_uri , $mpLength ) ; echo "You have searched for the profile of Mr. $name";
?>
Step 3: Now try http://servername/profiles/Jerry
(of course, there shouldn't be a file/folder in the server like "DOCROOT/profiles/Jerry" )
output: You have searched for the profile of Mr. Jerry
God Bless You!
Angelina Bell
04-Aug-2005 08:55
Warning:
$_SERVER['PHP_SELF'] and $_SERVER['SCRIPT_NAME'] may not always be set correctly.
Some web hosts implement php as a CGI in such a way that they can turn it on or off for each virtual domain. Several $_SERVER and $_ENV variable values may be incorrect for documents in subdirectory subdomains of these virtual domains.
An include-file function or constant, instead of PHP_SELF or some other predefined variable throughout a website, will make it easier to "fix" an entire website in case something changes.
<?php
function true_url_path() {
return $_ENV['SCRIPT_URL'];
}
?>
Or
<?php
define("TRUE_URL_PATH", $_ENV['SCRIPT_URL']);
?>
Gregory Boshoff
31-Jul-2005 02:41
$_SERVER['QUERY_STRING']
Does not contain XHTML 1.1 compliant ampersands i.e. &
So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.
// XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&', '&'), array('&', '&'),
$_SERVER['QUERY_STRING']);
New York PHP
24-Jul-2005 06:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.
The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.
The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).
The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
eustf at hotmail dot com
21-Jul-2005 08:05
REQUEST_URI not defined on Windows XP and IIS 5.1
I have seen different script on the web and in this list but they don't work fully. This one seems to work:
if(!isset($_SERVER['REQUEST_URI'])) {
$arr = explode("/", $_SERVER['PHP_SELF']);
$_SERVER['REQUEST_URI'] = "/" . $arr[count($arr)-1];
if ($_SERVER['argv'][0]!="")
$_SERVER['REQUEST_URI'] .= "?" . $_SERVER['argv'][0];
}
daniel at softel dot jp
15-Jul-2005 11:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
php at php-universe dot com
15-Jul-2005 05:11
While recently working on a file upload script, that works on moving files and resizing images based upon their extension, I found a great way to determine the file extension.
<?
function get_extension($filename)
{return (count($tmp = explode('.',basename($filename)))>1)?array_pop($tmp):'';
}foreach($_FILES as $files)
{if($files['error']==0)
{$ext = "<br />.".get_extension($files['name']);
echo $ext;
}}?>
This returns the file extension for each of the files uploaded, giving something like:
.jpg
.swf
andy dot gajetzki at gmail dot com
05-Jul-2005 06:22
I wanted to be able to embed a variable in the path. This is useful when, for example, images are rendered on the fly and you would like them to have different urls.
Here is an illustration:
www.somesite.com/image.php/IMAGETEXTHERE
This would return an image with the text after "image.php/" contained in it.
I could not recall the name of this feature, so I made a work-around in PHP...
<?
function getPathVariables() {
$sPathPS = $_SERVER[PHP_SELF];
$sPathFS = __FILE__;
$aPathPS = array_reverse(explode("/", $sPathPS));
$aPathFS = array_reverse(explode("/", $sPathFS));
$aImageArgs = array();
$x = 0;
while ( $aPathPS[$x] != $aPathFS[$x] && $aPathPS[$x] != $aPathFS[0] ) {
array_unshift($aImageArgs, $aPathPS[$x]) ;
$x++;
}
return $aImageArgs;
}
?>
This function will return an array containing each "/" delimited portion of the path after the script name itself.
notes at arbee dot co dot uk
27-Jun-2005 07:14
Note that $_SERVER['QUERY_STRING'] behaves differently under IIS/Apache.
In Apache (at least on Windows) it is ALWAYS set - if no query string was specified in the URL, $_SERVER['QUERY_STRING'] is initialised as an empty string.
In IIS, if no query string is included in the URL, $_SERVER['QUERY_STRING'] is NOT SET, so trying to access it without checking for its existence will generate notices.
koerner-familie at t-online dot de
21-Jun-2005 06:52
If you want to make a copy of $BLOBALS (e.g. to test whether which tariables were changed during script-runtime,
<?php $___debug_var_dump = $GLOBALS; ?>
will _NOT_ make a copy in PHP4 (tested with 4.3.11). Use
<?php $___debug_var_dump = array_merge($GLOBALS, array()); ?> instead, but ONLY for testing purpose.
Best regards, Peter
purplebz at hotmail dot com
19-Jun-2005 01:35
How to get $_SERVER['REQUEST_URI'] on IIS (WinXP):
if ( empty($_SERVER['REQUEST_URI']) ) {
$arr = explode("/", $_SERVER['PHP_SELF']);
$_SERVER['REQUEST_URI'] = $arr[count($arr)-1];
}
xangelusx at hotmail dot com
13-Jun-2005 01:03
A note about the QUERY_STRING variable when using IIS:
I have found that IIS does not handle large query strings gracefully when passed from PHP. In addition to truncating them to around 1024 kb, I have seen IIS actually add data from other server variables to the end of the truncated data.
This occurred on Windows 2000 server running IIS 5.0 and PHP 4.3.8. The problem did not occur when handled by Apache, even on another Windows server.
Note: I realize passing this much data is best accomplished using the POST method, which would avoid this problem all together. I'm merely detailing a problem that I came across.
I have created a page that includes the (very long) query string that was used and some of the results that I saw while testing. It can be viewed at http://www.csb7.com/test/php_iis_qs_limit/. I didn't want to include it here as it would stretch the page out significantly.
~Chris Bloom
mfyahya at gmail dot com
07-Jun-2005 06:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'
I'm not sure if this is a complete list though
mp at wds-tech dot de
02-Jun-2005 12:12
Also aviable is the $_SERVER['SERVER_ADDR'] which returns the current IP of the server the script is running on.
mike at go dot online dot pt
26-May-2005 12:58
In addition to what FX said about IE and Firefox, if you use the variable $PHP_SELF instead of $_SERVER['PHP_SELF'] that problem does not happen.
webKami (et) AKDomains.com
23-May-2005 11:47
PHP Secure Class to prevent XSS Attacks
Although this is not bullet proof but it would give you an idea on how to filter incoming data.
Copyleft : LGPL
Idea by: phpsec GROUP @ PHP|arch
Coded By: webKami
For those who are new to PHP and just heard of XSS attacks, this is the basic rule.
"NEVER EVER TRUST EXTERNAL DATA"
For this purpose I have coded a class that can be used to filter all external data, from POST, GET, COOKIE and even your own arrays.
An example is that if you need only integers from a certain parameter just request for integer
e.g. getVarInt("id")
You can even tell it to give you a default value if param is not set, so that your page would not FAIL in case of a NULL value
e.g. getVarInt("id",1)
You can also fetch data from a param array, like a set of colors
e.g. getVarInt("colors",0,0)
e.g. getVarInt("colors",0,1)
Get these variables in a loop limited by the count of that array's elements
e.g. getVarCount("colors")
The complete code of class and its usage can be found here
http://www.webkami.com/programming/php/php-secure-class-to-avoid-xss
I am posting the usage below.
<?
$req = new requestGet();
echo "Int:".$req->getVarInt("id")."<br />";
echo "Alpha:".$req->getVarAlpha("name",4)."<br />";
$req = new requestPost();
echo "Int:".$req->getVarInt("id")."<br />";
echo "Alpha:".$req->getVarAlpha("name",4)."<br />";
$req = new requestCookie();
echo "Int:".$req->getVarInt("id")."<br />";
echo "Alpha:".$req->getVarAlpha("name",4)."<br />";
$filter["id"]=4;
$filter["name"]="Ali";
$req = new requestFilter($filter);
echo "Int:".$req->getVarInt("id")."<br />";
echo "Alpha:".$req->getVarAlpha("name",4)."<br />";
?>
FX
23-May-2005 03:24
A form that has an action $_SERVER['PHP_SELF'];
in IE, it outputs as /test.php
but in FireFox it outputs as //test.php and so page can't be found.
Use basename($_SERVER['PHP_SELF']); instead .
sienkiewicz at gmail dot com
19-May-2005 07:18
Here is a very simple method of extracting all $_GET variables in a URL. This is useful when working with dynamic reports, that may need to be sorted, etc.
code:
foreach($_GET as $variable => $value) {
echo "Variable Name: " . $variable . " Value: $value<br>";
}
www dot php dot net at webdevelopers dot cz
12-May-2005 06:01
Simple function that selects "best" language for the user from the list of available languages:
function chooseLang($availableLangs) {
$pref=array();
foreach(split(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]) as $lang) {
if (preg_match('/^([a-z]+).*?(?:;q=([0-9.]+))?/i', $lang.';q=1.0', $split)) {
$pref[sprintf("%f%d", $split[2], rand(0,9999))]=strtolower($split[1]);
}
}
krsort($pref);
return array_shift(array_merge(array_intersect($pref, $availableLangs), $availableLangs));
}
echo 'BESTLANG: '.chooseLang(array('cs', 'sk', 'ru', 'en'));
Daniel "elixon" Sevcik
exaton at free dot fr
06-May-2005 11:23
With the arrival of the Google Web Accelerator, the problem of keeping track of users through $_SERVER['REMOTE_ADDR'] (for a much shorter while than with cookies) has reared its ugly head anew.
For those confronted with this issue, remember that Google implements the $_SERVER['HTTP_X_FORWARDED_FOR'] header giving the IP address of the connection that it proxies.
Hope this helps...
inbox at tanasity dot com
13-Apr-2005 06:23
Under Windows 2000, running IIS and PHP 4.3.10, $_SERVER['SCRIPT_NAME'] is not available, however $_SERVER['SCRIPT_FILENAME'] is present and seems to contain the same information.
javalizard at mac dot com
10-Apr-2005 04:02
My web host server will give my php the user preferred languages out over the order. This means that I had to write a function for ordering the languages based upon their "q" value (rank from 1..0, 1 being the most preferred). If you want an ordered list of user preferred languages use this function:
<?php
function orderedLanguages()
{
$languages = split(",", $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
$lang_q = Array();
foreach( $languages as $aLang ) {
$lang_array = split(";q=", trim( $aLang ) );
$lang = trim( $lang_array[0] );
if( !isset( $lang_array[1] ) )
$q = 1;
else
$q = trim($lang_array[1]);
$lang_q["$lang"] = (float)$q;
}
arsort($lang_q);
$i = 0;
$lang_index = Array();
foreach($lang_q as $lang => $q) {
$lang_index[$i] = $lang; $i++;
}
return $lang_q;
}
?>
While you can't reference the key by number, You can use foreach to pull elements. This will be in order. So getting the key with array_keys should work in the preferred order too. I've added a few extra lines of commented code for reordering the array into one(s) that reference the language by number (if you need it) :D
skrollster
26-Mar-2005 08:36
$_SERVER["REMOTE_USER"] and $_SERVER['PHP_AUTH_USER'] is the same variable i think..
anonymous
04-Mar-2005 02:12
I don't see the $_SERVER["REMOTE_USER"] listed in this document.
This displays the username used to login using .htaccess.
z dot stolar at gmail dot com
02-Mar-2005 02:05
It seems that if the current page was called with GET variables:
http://www.example.com/index.php?delete_id=12?add_id=34
and if, in that same page, you are about to submit another form, this time with POST method, assigning the form the action:
<?php $_SERVER['PHP_SELF'] ?>
will keep the GET variables at their place! (delete_id=12?add_id=34)
Rather, assign the form the action like this:
<?php echo $_SERVER['PHP_SELF'] ; ?>
this will call only index.php without any GET variables
27-Feb-2005 06:41
Matt Johnson says that one should never urldecode() $_GET data. This is incorrect.
If magic_quotes_gpc is turned off in php.ini, then you *do* need to urldecode() $_GET data.
Having magic_quotes_gpc turned off is considered good practise.
x_terminat_or_3 at [remove] yahoo.fr
27-Feb-2005 02:18
I didn't find it anywhere here and I was ready to bang my head on the wall until I found the solution!
So when you use a select with multiple options you have to cheat to let php recognize it.
When processing the request, php puts all selected options in the select object's name, but treats it like an array. If it is not an array, only the last option is remembered.
So to cheat you should append [ ] to the name of the select
<form .. ... ..>
<select multiple="multiple" name="myselect[]" size="3">
<option value="1">1st option</option>
<option value="2">2nd option</option>
<option value="3">3rd option</option>
...
Then in the processing part:
<?php
if(!empty[$_REQUEST['myselect']) print_r($_REQUEST['myselect']);
?>
Will show you the array with all the selected options
17-Feb-2005 03:30
grlprgrmmr wrote:
you can use these to reconstructed the current page url.
<?php
echo 'http';
if($_SERVER['HTTPS']=='on'){echo 's';}
echo '://'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
if($_SERVER['QUERY_STRING']>' '){echo '?'.$_SERVER['QUERY_STRING'];}
?>
______________
the $_SERVER['SERVER_PORT'] part should be changed to $_SERVER['HTTP_HOST']
Gregory Boshoff
13-Feb-2005 04:19
The Environment variable $ENV is useful for coding portable platform specific application constants.
// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';
define('PATH', $path);
echo PATH;
magotes[at]netcabo.pt
11-Feb-2005 07:09
Sorry if this is old news to some, but it might not be obvious at a first glance:
If you are using $_SERVER['remote_addr'] as a way to keep track of a logged-in user (this can be useful to avoid several types of hacking), remember that it might not be the user's actual IP address!
I was trying to implement a login feature that used this, storing the IP into a DB. It went smoothly while on a LAN, but wrecked havoc when accepting outter connections.
grlprgrmmr uses gmail
10-Feb-2005 11:05
you can use these to reconstructed the current page url.
<?php
echo 'http';
if($_SERVER['HTTPS']=='on'){echo 's';}
echo '://'.$_SERVER['SERVER_PORT'].$_SERVER['SCRIPT_NAME'];
if($_SERVER['QUERY_STRING']>' '){echo '?'.$_SERVER['QUERY_STRING'];}
?>
If $_SERVER['HTTPS']=='on' does not work for you,
try $_SERVER['SERVER_PORT']==443 (or whatever secure port is used)
JSP001
27-Jan-2005 02:15
Hi dotpointer,
I am new to php but I suggest a little modification of your script. Tell me what you think of it :
function getThisFile() {
[...]
/* last resort __FILE__ */
} else {
$strScript = __FILE__;
}
[...]
}
Thanks for this great function, I'll use it for my project !
Regards
niles AT atheos DOT net
26-Jan-2005 12:51
If your having problems returning $_SERVER variables using apache, be sure you enable:
ExtendedStatus On
in your httpd.conf file.
If it's off, then things like $_SERVER['HTTP_HOST'] won't be present.
marcus at lastcraft dot com
23-Jan-2005 04:02
The variable $php_errormsg is not populated if you have XDebug running.
roy dot rico at gmail dot com
18-Jan-2005 01:48
if you are trying to use $php_errormsg, it acts more like a function than it does a variable.
example
echo "<h1>";
$php_errormsg;
echo "</h1>";
will output:
<h1>[the php error]<h1>
however, this command
echo "<h1>" . $php_errormsg . "</h1>";
should produce the same thing, yet it produces
[the php error]<h1></h1>
not sure if this is a "feature" or a "bug"
dotpointer
09-Jan-2005 01:26
Running Xitami in Windows 2000 and PHP 4.3.7, nor PHP_SELF or SCRIPT_FILENAME is not availiable. Trying SCRIPT_NAME instead. Here is a function that returns the filename of a script without slashes. Good for use in HTML FORM ACTION=""-arguments...
function getThisFile() {
/* try to use PHP_SELF first... */
if (!empty($_SERVER['PHP_SELF'])) {
$strScript = $_SERVER['PHP_SELF'];
/* otherwise, try SCRIPT_NAME */
} else if (!empty($_SERVER['SCRIPT_NAME'])) {
$strScript = @$_SERVER['SCRIPT_NAME'];
/* last resort - quit out and return nothing */
} else {
return null;
}
/* fint last frontslash in filename */
$intLastSlash = strrpos($strScript, "/");
/* check if last backslash is more far away in filename */
if (strrpos($strScript, "\\")>$intLastSlash) {
/* if so, use the backslash position instead */
$intLastSlash = strrpos($strScript, "\\");
}
/* cut out from the last slash and to the end of the filename */
return substr($strScript, $intLastSlash+1, strlen($strScript));
}
Tested on PHP 4.3.7/Win32 and PHP 5.0.3/Linux.
You may add more filepaths to the first if-section
to get more chances to catch up the filename if you can.
Matt Johnson
25-Dec-2004 04:50
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!
Evil PHP:
<?php
$term = urldecode($_GET['sterm']);
?>
Good PHP:
<?php
$term = $_GET['sterm'];
?>
The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!
Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.
Hint: script.php?sterm=%2527 [...]
PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!
This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
mrnopersonality at yahoo dot com
19-Oct-2004 08:13
Nothing about the message-body ...
You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.
Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
hfuecks at phppatterns dot com
06-Sep-2004 12:21
Using Apache/mod_ssl, there are further environment variables available to check for an SSL connection (can be more useful than $_SERVER['SERVER_PORT']), documented here: http://www.modssl.org/docs/2.8/ssl_reference.html#ToC25
To test whether the client connected with SSL I can use $_SERVER['HTTPS'] e.g (with redirect to secured, current URL);
<?php
if ( !isset($_SERVER['HTTPS']) || strtolower($_SERVER['HTTPS']) != 'on' ) {
header ('Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
exit();
}
?>
boaz at babylon dot com
30-Aug-2004 07:13
You can add $_SERVER["DOCUMENT_ROOT"] to IIS by editing the Environment Variables of your Windows server (was tested on WinXP SP2).
Right click on My Computer >> Properties >> Advanced.
In the System variables click on 'New' and Type in the name field 'DOCUMENT_ROOT' and in the value field the path to your IIS document root folder.
Don't forget to restart your Windows (IIS restart won't load the new settings).
david at grant dot org dot uk
12-May-2004 05:34
$_SERVER['DOCUMENT_ROOT'] *is* supported by IIS, although only when running PHP as an ISAPI module.
youdontmeanmuch [at] yahoo.com
05-Apr-2004 09:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
mortoray at ecircle-ag dot com
18-Dec-2003 09:32
The RAW / uninterpreted HTTP POst information can be accessed with:
$GLOBALS['HTTP_RAW_POST_DATA']
This is useful in cases where the post Content-Type is not something PHP understands (such as text/xml).
josh,endquote,com
03-Dec-2003 03:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:
if(!isset($_SERVER['REQUEST_URI'])) {
$_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}
| |