Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

Predefined Variables

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.

Server variables: $_SERVER

Замечание: 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_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.

'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.

Note that when using ISAPI with IIS, the value will be off if the request was not made 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.

Environment variables: $_ENV

Замечание: 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.

HTTP Cookies: $_COOKIE

Замечание: 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.

HTTP GET variables: $_GET

Замечание: 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.

HTTP POST variables: $_POST

Замечание: 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.

HTTP File upload variables: $_FILES

Замечание: 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.

Request variables: $_REQUEST

Замечание: 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.

Session variables: $_SESSION

Замечание: 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.

Global variables: $GLOBALS

Замечание: $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.

The previous error message: $php_errormsg

$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 Classes> <List of Reserved Words
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
Predefined Variables
martin dot szwarc at gmail dot com
02-Nov-2007 08:40
For a pretty browser name:

if (stristr($_SERVER['HTTP_USER_AGENT'],"firefox")) {
$agent = "Firefox";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"safari")) {
$agent = "Safari";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"msie 7")) {
$agent = "IE 7";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"opera")) {
$agent = "Opera";
}
elseif (stristr($_SERVER['HTTP_USER_AGENT'],"msie 6")) {
$agent = "IE 6";
}
else {
$agent = "UNKNOWN";
}
root at mantoru dot de
01-Nov-2007 07:59
Note that some headers will be checked for validity (by Apache, I suppose) before showing up in $_SERVER -- If-Modified-Since for example.

<?php
$lastmod
= gmdate('D, d M Y H:i:s', filemtime('somefile'));
header("Last-Modified: $lastmod");
?>

This WON'T work, "GMT" is missing. Internet Explorer auto-fixes this by adding GMT, while Firefox resends this data as-is. (So an If-Modified-Since-header is sent, but neither shows up in $_SERVER nor in apache_request_headers()). This would be correct:

<?php
$lastmod
= gmdate('D, d M Y H:i:s', filemtime('somefile')) . 'GMT';
header("Last-Modified: $lastmod");
?>
jsan
19-Oct-2007 12:39
@White-Gandalf: one can control this behavior by setting:

UseCanonicalName On|Off

in their apache config (at least, on *ix platforms).

On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.

Off => Whatever was in the Host: header sent by the client.
White-Gandalf
16-Oct-2007 07:01
'SERVER_NAME' does NOT necessarily refer to the name of a virtual host or any other things defined in the apache config.
Instead it simply takes the value of the "Host:" entry of the HTTP-header sent by the client.
At least with apache version 2.2.5 on Windows.
doheth.co.uk
13-Oct-2007 04:15
slight improvement to the example by 'andres at andresj dot ath dot cx' for determining the path to the currently script.

Previous version:

<?php
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
?>

Windows uses back-slash to indicate folders, so this didn't work on localhost for me. All you need to do is convert any back-slashes to forward-slashes. This should work on all systems:

<?php
// If your script is included from another script:
$included_file = str_replace('\\', '/', __FILE__);
$included_directory = substr($included_file, 0, strrpos($included_file, '/'));
?>
Error Code
05-Oct-2007 01:30
An easy coding, but usefull

<?
$agent       = $_SERVER['HTTP_USER_AGENT'];
$ip          = $_SERVER['REMOTE_ADDR'];
$port        = $_SERVER['REMOTE_PORT'];
$d           = date ('dS \of F Y h:1:s A');

echo "Your IP : $ip<br>";
echo "You are using : $agent<br>";
echo "You are connected thruogh port : $port<br>";
echo "Today is : $d";

$fp = fopen("data", "a");
fwrite($fp, "\n");
fwrite($fp, "\n");
fwrite($fp, "\n");
fwrite($fp, "Your IP : $ip");
fwrite($fp, "\n");
fwrite($fp, "You are using : $agent");
fwrite($fp, "\n");
fwrite($fp, "You are connected thruogh port : $port");
fwrite($fp, "\n");
fwrite($fp, "Today is : $d");
fwrite($fp, "\n");
fwrite($fp, "***********________________***********");

?>

it can show these information in your page and it saves it
you can also hide these info by removing

echo "Your IP : $ip<br>";
echo "You are using : $agent<br>";
echo "You are connected thruogh port : $port<br>";
echo "Today is : $d";

or you can change the coding and let it save the info in the database mysql_connect (
cancausecancerr at yahoo dot com dot cn
01-Oct-2007 02:23
The setGetVar() function posted above has an error in it. If $var exists in the path but not as a variable then the URI is returned unaltered:

Example:
URI=http://localhost/images/upload/image.php?page=1403
setGetVar('image','40')

'image' is found by strstr($request_uri, $var) but since its not in the variables;  preg_replace returns the original uri.

<?php
function setGetVar($var, $val){
   
$request_uri = $_SERVER["REQUEST_URI"];
    if(
strstr($request_uri, $var)) {
        return
preg_replace("/$var=[\\d\\w]*/", "$var=$val", $request_uri);
    } elseif(
strstr($request_uri, "?")) {
        return
$request_uri . "&" . $var . "=" . $val;
    } else {
        return
$request_uri . "?" . $var . "=" . $val;
    }
}
?>

This is the fixed copy of the function. If $var is found then the preg_replace is executed but this time the result URI is compared against the initial URI. If they are the same then $var wasn't replaced and the script continues on to append it to the URI.

<?php
function setGetVar($var, $val) {
   
$request_uri = $_SERVER["REQUEST_URI"];
    if (
strstr($request_uri, $var)) {
           
$newURI = preg_replace("/$var=[\\d\\w]*/", "s$var=$val", $request_uri);
        if (
$newURI != $request_uri) return $newURI;
    }
    if (
strstr($request_uri, "?")) return $request_uri . "&" . $var . "=" . $val;
    else return
$request_uri . "?" . $var . "=" . $val;
}
?>
phpnotes dot 20 dot zsh at spamgourmet dot com
21-Sep-2007 08:45
The headers sent by the browser will be stored in the $_SERVER array -- they will get capitalized and prefixed with HTTP. So a header like "X-Foo-Bar: Baz" will result in <?php $_SERVER['HTTP_X_FOO_BAR'] = 'Baz';?>. This is why you should use isset before using e.g. HTTP_ACCEPT_LANGUAGE, 'cause it may not be set.

The only exception I know from that is HTTP_X_ORIGINAL_URI, which is always set and holds the current URL without querystring. But you can't trust that too because it can be overriden by sending a X-Original-URI header.
anonymous
09-Aug-2007 08:48
To get the filename use:

basename($_SERVER['SCRIPT_FILENAME'])
andres at andresj dot ath dot cx
05-Aug-2007 09:41
To get the directory of the current script: (I think this is a little more resource-friendly, but then again with all the fast computers available, it does not matter so much...)
<?
// For the script that is running:
$script_directory = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], '/'));
// If your script is included from another script:
$included_directory = substr(__FILE__, 0, strrpos(__FILE__, '/'));
echo $script_directory . '<br />';
echo $included_directory . '<br />';
?>
If you have a script that only includes the script written above in a directory called 'includer', and I access it from a web browser, this will be what I see:

/path/to/includer/
/path/to/included/
From Under A Rock...
31-Jul-2007 01:49
This small snippet will build the current script's url.  No muss, no fuss:

<?php

$self_url
= sprintf('http%s://%s%s',
  (isset(
$_SERVER['HTTPS']) && $_SERVER['HTTPS'] == TRUE ? 's': ''),
 
$_SERVER['HTTP_HOST'],
 
$_SERVER['REQUEST_URI']
);

?>
opez.org
30-Jul-2007 08:14
I couldn't find a better way... Here is a simple line of code that will give you the path to the current file/script:

<?php

$path_only
= implode("/", (explode('/', $_SERVER["SCRIPT_FILENAME"], -1)));

print
$path_only; // /home/worldpeace/public_html/test

print $_SERVER["SCRIPT_FILENAME"]; // /home/worldpeace/public_html/test/test.php

?>

I use this to build INCLUDE commands that call a file determined by a variable [ path + / + file ]. Dont forget the /

I hope this inspires someone.
mathiasrav at gmail dot com
28-Jul-2007 01:31
Based on dlyaza's snippet posted at 22-Oct-2006 12:33, here's getip() which gets the IP, first checking some known custom proxy headers for validity and then falling back to REMOTE_ADDR if none are found/match.

<?php
function getip() {
  static
$ip = false;
  if (
$ip !== false) return $ip;
  foreach (array(
'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $aah) {
    if (!isset(
$_SERVER[$aah])) continue;
   
$curip = $_SERVER[$aah];
   
$curip = explode('.', $curip);
    if (
count($curip) !== 4) break; // If they've sent at least one invalid IP, break out
   
foreach ($curip as &$sup) if (($sup = intval($sup)) < 0 or $sup > 255) break 2;
   
$curip_bin = $curip[0] << 24 | $curip[1] << 16 | $curip[2] << 8 | $curip[3];
    foreach (array(
     
//    hexadecimal ip  ip mask
     
array(0x7F000001,     0xFFFF0000), // 127.0.*.*
     
array(0x0A000000,     0xFFFF0000), // 10.0.*.*
     
array(0xC0A80000,     0xFFFF0000), // 192.168.*.*
   
) as $ipmask) {
      if ((
$curip_bin & $ipmask[1]) === ($ipmask[0] & $ipmask[1])) break 2;
    }
    return
$ip = $curip;
  }
  return
$ip = $_SERVER['REMOTE_ADDR'];
}
?>
jmv a jmvware d com
25-Jul-2007 12:32
The preceding note by krausbn works well, but be aware that whatever you use to parse it needs to urldecode the data
krausbn at php dot net
12-Jul-2007 04:35
On very low level POSTs (AJAX, XML RPC etc.) the $GLOBALS['HTTP_RAW_POST_DATA'] var might not contain data because of your php.ini settings. If that's the case you can use php://input to retrieve this low level data:

    // read raw POST data
$input = file_get_contents('php://input');
seb at omegasoft dot co dot uk
11-Jul-2007 07:19
More attractive way for displaying a URL

<?php

function get_url($show_port = false)
{
    if(
$_SERVER['HTTPS'])
    {
       
$my_url = 'https://';
    }
    else
    {
       
$my_url = 'http://';
    }

   
$my_url .= $_SERVER['HTTP_HOST'];

    if(
$show_port)
    {
       
$my_url .= ':' . $_SERVER['SERVER_PORT'];
    }

   
$my_url .= $_SERVER['SCRIPT_NAME'];

    if(
$_SERVER['QUERY_STRING'] != null)
    {   
       
$my_url .= '?' . $_SERVER['QUERY_STRING'];
    }

    return
$my_url;
}

echo
get_url(); // Outputs: http://localhost/
echo get_url(true); // Outputs: http://localhost:80/

?>
djaped at yahoo dot com
19-Jun-2007 07:49
Current Page URL
<?php
$urlh
= getenv(HTTP_HOST);
$url = "http://$urlh";
echo
' '.$url.$_SERVER['SCRIPT_NAME'];
?>
pecili
mike
12-Jun-2007 01:19
<?php
   
/*
    Simple function to get current page URL using comman PHP variables
   
    Function inputs:
        $base if set to true will add the basename to the URL
        $www if set to true will add www. to host if not found
        $query if set to true will add the query string to the URL
        $echo if set to true will echo the URL instead of just returning it
    */
   
function get_url($base = true, $www = true, $query = true, $echo = false){
       
$URL = ''; //open return variable
       
$URL .= (($_SERVER['HTTPS'] != '') ? "https://" : "http://"); //get protocol
       
$URL .= (($www == true && !preg_match("/^www\./", $_SERVER['HTTP_HOST'])) ? 'www.'.$_SERVER['HTTP_HOST'] : $_SERVER['HTTP_HOST']); //get host
       
$path = (($_SERVER['REQUEST_URI'] != '') ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']); //tell the function what path variable to use
       
$URL .= ((pathinfo($path, PATHINFO_DIRNAME) != '/') ? pathinfo($path, PATHINFO_DIRNAME).'/' : pathinfo($path, PATHINFO_DIRNAME)); //set up directory
       
$URL .= (($base == true) ? pathinfo($path, PATHINFO_BASENAME) : ""); //add basename
       
$URL  = preg_replace("/\?".preg_quote($_SERVER['QUERY_STRING'])."/", "", $URL); //remove query string if found in url
       
$URL .= (($query == true && $_SERVER['QUERY_STRING'] != '') ? "?".$_SERVER['QUERY_STRING'] : ""); //add query string
       
if($echo == true){
            echo
$URL;
        }else{
            return
$URL;
        }
    }
   
   
/* Example */
   
$page_url = get_url();
    echo
$page_url;
?>
Mike
22-May-2007 02:27
Using HTTP_REFERER and parse_url() to display the host of the URL that a vistor came to your site from.

<?php
   
if($_SERVER['HTTP_REFERER'] != ''){
       
$URL = parse_url($_SERVER['HTTP_REFERER']);
        echo
"Welcome, <b>".$URL['host']."</b> visitor!";
    }
?>
deceze at gmail dot YesThatsGoogleMail dot com
11-Apr-2007 07:37
If you're working with $_GET a lot and need to preserve already set variables in a link for the next page, this function is pretty handy for simplifying the process of generating a new URL:

string setUrlVariables([string var, string value], [varN, valueN], ...)

<?php

function setUrlVariables() {
 
$arg = array();
 
$string = "?";
 
$vars = $_GET;
  for (
$i = 0; $i < func_num_args(); $i++)
   
$arg[func_get_arg($i)] = func_get_arg(++$i);
  foreach (
array_keys($arg) as $key)
   
$vars[$key] = $arg[$key];
  foreach (
array_keys($vars) as $key)
    if (
$vars[$key] != "") $string.= $key . "=" . $vars[$key] . "&";
  if (
SID != "" && SID != "SID" && $_GET["PHPSESSID"] == "")
   
$string.= htmlspecialchars(SID) . "&";

  return
htmlspecialchars(substr($string, 0, -1));
}

?>

You use it like this:

<a href="nextpage.php<?php echo setUrlVariables(); ?>">Link</a>

In this case setUrlVariables() will simply add all the $_GET variables of the current page/URL and even takes care of the PHPSESSID if you use one (and didn't change the default variable name). The above HREF would complete to e.g.:

"nextpage.php?var=21&amp;PHPSESSID=BI89J"

If you supply arguments, do it like this:

<?php echo setUrlVariables("user", "foobar"); ?>

This would complete the HREF to e.g.:

"nextpage.php?user=foobar&amp;var=21&amp;PHPSESSID=BI89J"

Unsetting variables works by supplying an empty value:

<?php echo setUrlVariables("var", ""); ?>

"nextpage.php?user=foobar&amp;PHPSESSID=BI89J"

setUrlVariables() also makes sure it produces "pretty URLs", so it doesn't output any unnecessary garbage. ;)

<?php
  session_destroy
();
  echo
setUrlVariables("user", "");
?>

"nextpage.php"
danvasile at pentest dot ro
21-Mar-2007 01:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:

<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Of course, this should be done before any html tag or php echo/print.
bosmeew at gmail dot com
18-Feb-2007 06:43
To get the server address, you can use $_SERVER['SERVER_ADDR']. However, this only works when your PHP process is running on a webserver, not when running PHP as CLI. Here is a function which will also return the server address when running on linux (eth0 is hardcoded as the network interface, modify if necessary).

<?php

function getServerAddress() {
    if(
$_SERVER['SERVER_ADDR']) {
        return
$_SERVER['SERVER_ADDR'];
    }
   
   
$ifconfig = shell_exec('/sbin/ifconfig eth0');
   
preg_match('/addr:([\d\.]+)/',$ifconfig,$match);
   
    return
$match[1];
}

?>
borg at sven-of-nine dot de
30-Jan-2007 03:22
Simple function to determine if a visitor is an agent or not

function isbot($agent="")
    {
    //Handfull of Robots
    $bot_array      =array("jeevesteoma",
                                   "msnbot",
                                   "slurp",
                                   "jeevestemoa",
                                   "gulper",
                                   "googlebot",
                                   "linkwalker",
                                   "validator",
                                   "webaltbot",
                                   "wget");
    //no agent given => read from globals
    if ($agent=="")
        {
        @$agent=$_SERVER["HTTP_USER_AGENT"];
        }
    //replace all but alpha
    $agent=strtolower(preg_replace("/[^a-zA-Z _]*/","",$agent));
    //check f
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571