国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > PHP > 正文

動態(tài)網(wǎng)頁制作學(xué)習(xí):PHP預(yù)定義變量

2024-05-04 23:03:40
字體:
供稿:網(wǎng)友

預(yù)定義變量
自 php 4.1.0 起,取得外部變量的首選方法是用下面提及的超全局變量。在此之前,人們要么依賴 register_globals,要么就是長長的預(yù)定義 php 數(shù)組($http_*_vars)。自 php 5.0.0 起,長格式的 php 預(yù)定義變量可以通過設(shè)置 register_long_arrays 來屏蔽。

服務(wù)器變量:$_server
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_server_vars。

$_server 是一個包含諸如頭信息(header)、路徑(path)和腳本位置(script locations)的數(shù)組。數(shù)組的實體由 web 服務(wù)器創(chuàng)建。不能保證所有的服務(wù)器都能產(chǎn)生所有的信息;服務(wù)器可能忽略了一些信息,或者產(chǎn)生了一些未在下面列出的新的信息。這意味著,大量的這些變量在 cgi 1.1 規(guī)范中說明,所以應(yīng)該仔細(xì)研究一下。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_server; 訪問它,就如同使用 $http_server_vars 一樣。

$http_server_vars 包含著同樣的信息,但是不是一個自動全局變量(注意:$http_server_vars 和 $_server 是不同的變量,php 處理它們的方式不同)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_server 和 $http_server_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

或許會發(fā)現(xiàn)下面列出的某些 $_server 元素并不可用。注意,如果以命令行方式運(yùn)行 php,下面列出的元素幾乎沒有有效的(或是沒有任何實際意義的)。

“php_self”
當(dāng)前正在執(zhí)行腳本的文件名,與 document root 相關(guān)。舉例來說,在 url 地址為 http://example.com/test.php/foo.bar 的腳本中使用 $_server['php_self'] 將會得到 /test.php/foo.bar 這個結(jié)果。__file__ 常量包含當(dāng)前(例如包含)文件的絕對路徑和文件名。

如果 php 以命令行方式運(yùn)行,該變量在 php 4.3.0 之前無效。

“argv”
傳遞給該腳本的參數(shù)。當(dāng)腳本運(yùn)行在命令行方式時,argv 變量傳遞給程序 c 語言樣式的命令行參數(shù)。當(dāng)調(diào)用 get 方法時,該變量包含請求的數(shù)據(jù)。

“argc”
包含傳遞給程序的命令行參數(shù)的個數(shù)(如果運(yùn)行在命令行模式)。

“gateway_interface”
服務(wù)器使用的 cgi 規(guī)范的版本。例如,“cgi/1.1”。

“server_name”
當(dāng)前運(yùn)行腳本所在服務(wù)器主機(jī)的名稱。如果該腳本運(yùn)行在一個虛擬主機(jī)上,該名稱是由那個虛擬主機(jī)所設(shè)置的值決定。

“server_software”
服務(wù)器標(biāo)識的字串,在響應(yīng)請求時的頭信息中給出。

“server_protocol”
請求頁面時通信協(xié)議的名稱和版本。例如,“http/1.0”。

“request_method”
訪問頁面時的請求方法。例如:“get”、“head”,“post”,“put”。

注: 如果請求的方式是 head,php 腳本將在送出頭信息后中止(這意味著在產(chǎn)生任何輸出后,不再有輸出緩沖)。

“request_time”
請求開始時的時間戳。從 php 5.1.0 起有效。

“query_string”
查詢(query)的字符串(url 中第一個問號 ? 之后的內(nèi)容)。

“document_root”
當(dāng)前運(yùn)行腳本所在的文檔根目錄。在服務(wù)器配置文件中定義。

“http_accept”
當(dāng)前請求的 accept: 頭信息的內(nèi)容。

“http_accept_charset”
當(dāng)前請求的 accept-charset: 頭信息的內(nèi)容。例如:“iso-8859-1,*,utf-8”。

“http_accept_encoding”
當(dāng)前請求的 accept-encoding: 頭信息的內(nèi)容。例如:“gzip”。

“http_accept_language”
當(dāng)前請求的 accept-language: 頭信息的內(nèi)容。例如:“en”。

“http_connection”
當(dāng)前請求的 connection: 頭信息的內(nèi)容。例如:“keep-alive”。

“http_host”
當(dāng)前請求的 host: 頭信息的內(nèi)容。

“http_referer”
鏈接到當(dāng)前頁面的前一頁面的 url 地址。不是所有的用戶代理(瀏覽器)都會設(shè)置這個變量,而且有的還可以手工修改 http_referer。因此,這個變量不總是真實正確的。

“http_user_agent”
當(dāng)前請求的 user-agent: 頭信息的內(nèi)容。該字符串表明了訪問該頁面的用戶代理的信息。一個典型的例子是:mozilla/4.5 [en] (x11; u; linux 2.2.9 i586)。也可以使用 get_browser() 得到此信息。

“https”
如果腳本是通過 https 協(xié)議被訪問,則被設(shè)為一個非空的值。

“remote_addr”
正在瀏覽當(dāng)前頁面用戶的 ip 地址。

“remote_host”
正在瀏覽當(dāng)前頁面用戶的主機(jī)名。反向域名解析基于該用戶的 remote_addr。

注: 必須配置 web 服務(wù)器來建立此變量。例如 apache 需要在 httpd.conf 中有 hostnamelookups on。參見 gethostbyaddr()。

“remote_port”
用戶連接到服務(wù)器時所使用的端口。

“script_filename”
當(dāng)前執(zhí)行腳本的絕對路徑名。

注: 如果腳本在 cli 中被執(zhí)行,作為相對路徑,例如 file.php 或 ../file.php,$_server['script_filename'] 將包含用戶指定的相對路徑。

 

“server_admin”
該值指明了 apache 服務(wù)器配置文件中的 server_admin 參數(shù)。如果腳本運(yùn)行在一個虛擬主機(jī)上,則該值是那個虛擬主機(jī)的值。

“server_port”
服務(wù)器所使用的端口。默認(rèn)為“80”。如果使用 ssl 安全連接,則這個值為用戶設(shè)置的 http 端口。

“server_signature”
包含服務(wù)器版本和虛擬主機(jī)名的字符串。

“path_translated”
當(dāng)前腳本所在文件系統(tǒng)(不是文檔根目錄)的基本路徑。這是在服務(wù)器進(jìn)行虛擬到真實路徑的映像后的結(jié)果。

注: php 4.3.2 之后,path_translated 在 apache 2 sapi 模式下不再和 apache 1 一樣隱含賦值,而是若 apache 不生成此值,php 便自己生成并將其值放入 script_filename 服務(wù)器常量中。這個修改遵守了 cgi 規(guī)范,path_translated 僅在 path_info 被定義的條件下才存在。

apache 2 用戶可以使用 httpd.conf 中的 acceptpathinfo on 來定義 path_info。

“script_name”
包含當(dāng)前腳本的路徑。這在頁面需要指向自己時非常有用。__file__ 包含當(dāng)前文件的絕對路徑和文件名(例如包含文件)。

“request_uri”
訪問此頁面所需的 uri。例如,“/index.html”。

“php_auth_digest”
當(dāng)作為 apache 模塊運(yùn)行時,進(jìn)行 http digest 認(rèn)證的過程中,此變量被設(shè)置成客戶端發(fā)送的“authorization”http 頭內(nèi)容(以便作進(jìn)一步的認(rèn)證操作)。

“php_auth_user”
當(dāng) php 運(yùn)行在 apache 或 iis(php 5 是 isapi)模塊方式下,并且正在使用 http 認(rèn)證功能,這個變量便是用戶輸入的用戶名。

“php_auth_pw”
當(dāng) php 運(yùn)行在 apache 或 iis(php 5 是 isapi)模塊方式下,并且正在使用 http 認(rèn)證功能,這個變量便是用戶輸入的密碼。

“auth_type”
當(dāng) php 運(yùn)行在 apache 模塊方式下,并且正在使用 http 認(rèn)證功能,這個變量便是認(rèn)證的類型。

 

環(huán)境變量:$_env
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_env_vars。

在解析器運(yùn)行時,這些變量從環(huán)境變量轉(zhuǎn)變?yōu)?php 全局變量名稱空間(namespace)。它們中的許多都是由 php 所運(yùn)行的系統(tǒng)決定。完整的列表是不可能的。請查看系統(tǒng)的文檔以確定其特定的環(huán)境變量。

其它環(huán)境變量(包括 cgi 變量),無論 php 是以服務(wù)器模塊或是以 cgi 處理方式運(yùn)行,都在這里列出了。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_env; 來訪問它,就如同使用 $http_env_vars 一樣。

$http_env_vars 包含著同樣的信息,但是不是一個自動全局變量(注意:$http_env_vars 和 $_env 是不同的變量,php 處理它們的方式不同)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_env 和 $http_env_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

http cookies:$_cookie
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_cookie_vars。

通過 http cookies 傳遞的變量組成的數(shù)組。是自動全局變量。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_cookie; 來訪問它,就如同使用 $http_cookie_vars 一樣。

$http_cookie_vars 包含著同樣的信息,但是不是一個自動全局變量(注意:$http_cookie_vars 和 $_cookie 是不同的變量,php 處理它們的方式不同)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_cookie 和 $http_cookie_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

http get 變量:$_get
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_get_vars。

通過 http get 方法傳遞的變量組成的數(shù)組。是自動全局變量。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_get; 來訪問它,就如同使用 $http_get_vars 一樣。

$http_get_vars 包含著同樣的信息,但是不是一個自動全局變量(注意:$http_get_vars 和 $_get 是不同的變量,php 處理它們的方式不同)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_get 和 $http_get_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

http post 變量:$_post
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_post_vars。

通過 http post 方法傳遞的變量組成的數(shù)組。是自動全局變量。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_post; 來訪問它,就如同使用 $http_post_vars 一樣。

$http_post_vars 包含著同樣的信息,但是不是一個自動全局變量(注意:$http_post_vars 和 $_post 是不同的變量,php 處理它們的方式不同)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_post 和 $http_post_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

http 文件上傳變量:$_files
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_post_files。

通過 http post 方法傳遞的已上傳文件項目組成的數(shù)組。是自動全局變量。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_files; 來訪問它,就如同使用 $http_post_files 一樣。

$http_post_files 包含著同樣的信息,但是不是一個自動全局變量(請注意 php 是把 $http_post_files 和 $_files 這兩個變量當(dāng)作不同的變量來處理的)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_files 和 $http_post_files 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

request 變量:$_request
注: 在 php 4.1.0 及以后版本使用。之前的版本,沒有等價的數(shù)組。

注: 在 php 4.3.0 之前,$_files 也被包括在 $_request 數(shù)組中。

此關(guān)聯(lián)數(shù)組包含 $_get,$_post 和 $_cookie 中的全部內(nèi)容。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味著它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_request; 來訪問它。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_request 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

session 變量:$_session
注: 在 php 4.1.0 及以后版本使用。之前的版本,使用 $http_session_vars。

包含當(dāng)前腳本中 session 變量的數(shù)組。參閱 session 函數(shù)文檔以獲得更多信息。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $_session; 來訪問它,就如同使用 $http_session_vars 一樣。

$http_session_vars 包含著同樣的信息,但是不是一個自動全局變量(請注意 php 是把 $http_session_vars 和 $_session 這兩個變量當(dāng)作不同的變量來處理的)。

如果設(shè)置了 register_globals 指令,這些變量也在所有腳本中可用;也就是,分離了 $_session 和 $http_session_vars 數(shù)組。相關(guān)信息,請參閱安全的相關(guān)章節(jié)使用 register globals。這些單獨的全局變量不是自動全局變量。

global 變量:$globals
注: $globals 在 php 3.0.0 及以后版本中適用。

由所有已定義全局變量組成的數(shù)組。變量名就是該數(shù)組的索引。

這是一個“superglobal”,或者可以描述為自動全局變量。這只不過意味這它在所有的腳本中都有效。在函數(shù)或方法中不需要使用 global $globals; 來訪問它。

前一個錯誤消息:$php_errormsg
$php_errormsg 是包含 php 產(chǎn)生的上一錯誤消息內(nèi)容的變量。該變量在發(fā)生錯誤并且 track_errors 選項打開(默認(rèn)為關(guān)閉)后才有效。

 


 add a note user contributed notes
預(yù)定義變量
danvasile at pentest dot ro
22-mar-2007 04: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 10: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 07: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ür intersections
    return((bool)count(array_intersect(explode(" ",$agent),$bot_array)));
    }
joe marty
25-jan-2007 03:53
i think it is very important to note that php will automatically replace dots ('.') and spaces (' ') with underscores ('_') in any incoming post or get (or request) variables.

this page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php

the reason is that '.' and ' ' are not valid characters to use in a variable name.  this is confusing to many people, because most people use the format $_post['name'] to access these values.  in this case, the name is not used as a variable name but as an array index, in which those characters are valid.

however, if the register_globals directive is set, these names must be used as variable names.  as of now, php converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.

if you want to use:
<input name="title for page3.php" type="text">

the value you will get in your post array, for isntance would be:
$_post['title_for_page3_php']
neosmart technologies
18-nov-2006 10:22
the *only* way to make request_uri work as a 100% apache-compliant server variable on iis/windows is to use an isapi filter - as documented at http://neosmart.net/blog/archives/291 . the various steps mentioned below *completely* fail when a rewrite engine is employed, since iis will *never* return a non-existent path (i.e. the actual pretty-uri used) via its server variables.

this also applies to accessing index.php via a folder.
for instance, calls made to /folder/ will appear as /folder/index.php and not /folder/.

the fix is to use the isapi filter provided at http://neosmart.net/blog/archives/291

you don't have to modify any of the actual scripts once this filter is in place - it automatically intercepts calls to request_uri and replaces them with the actual user-entered path.
me at tommygeorge dot com
10-nov-2006 12:59
i'm sure this is elsewhere, but since 'chris dot chaudruc at gmail dot com' posted his example, i thought i would share a quick function i use to force https protocol on a page, without having to know the scripts name...

<?php
function forcehttps()
{
    if( $_server['https'] != "on" ) 
    {
       $new_url = "https://" . $_server['server_name'] . $_server['request_uri'];
       header("location: $new_url");
       exit;
    }
}
?>

correct me if part of this doesn't work right. i've always used *nix based servers for php, so i might not be aware of certain windows limitations. thanks.
uili - e-info(at)tunenami.com
25-oct-2006 06:34
andy staudacher may have addressed this in his bug fix but just for clarifacation when reading a cookie $_cookie reads only the most accurate domain including sub domain. if you have cookies for .bar.com and foo.bar.com and the user is at foo.bar.com $_cookie only returns the cookie data from foo.bar.com but if the user is at www.bar.com the data from .bar.com will be read if there is no cookie for www.bar.com.
dlyaza at yahoo dot com
23-oct-2006 03:33
get real ip address; if some one know more than below, let us to see

if (getenv('http_client_ip')) {
$ip = getenv('http_client_ip');
}
elseif (getenv('http_x_forwarded_for')) {
$ip = getenv('http_x_forwarded_for');
}
elseif (getenv('http_x_forwarded')) {
$ip = getenv('http_x_forwarded');
}
elseif (getenv('http_forwarded_for')) {
$ip = getenv('http_forwarded_for');
}
elseif (getenv('http_forwarded')) {
$ip = getenv('http_forwarded');
}
else {
$ip = $_server['remote_addr'];
}
seanhickey at gmail dot com
20-sep-2006 05:46
note that class objects will not be in the $globals array until *after* the classe's constructor returns.

<?php
class a
{
    public function __construct()
    {
        var_dump($globals);
    }
}

$a = new a;
var_dump($globals);
?>

the first var_dump() inside the __construct() method will not contain the value of $a, while the second one will.
alexander hars
19-sep-2006 05:16
if you want to use a form with multiple checkboxes (e.g. one per row) and assign the same name to each checkbox then the name needs to end with []. this tells php to put all checked values into an array variable.
for example:
<input type="checkbox" name="id[]" value="value_1">
<input type="checkbox" name="id[]" value="value_2">
..
<input type="checkbox" name="id[]" value="value_x">

you can now retrieve all values by using:
   $values = $_post['id'];

if the name does not end with [], then only a single value will be available via the $_post variable even if the user checks several checkboxes.
trevor
09-aug-2006 01:49
i needed to do the exact same thing as jwl007 (sort by clicking links) but i needed it to append the variable to the query string if it didn't already exist. here's the function i'm using:

<?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;
    }
}
?>

<a href="<?php echo setgetvar("orderby", "lname"); ?>">sort by last name</a>
<a href="<?php echo setgetvar("orderby", "fname"); ?>">sort by first name</a>
jmurphy at hsdirect dot co dot uk
26-jul-2006 10:17
as above the $_server['request_uri']

is replaced in windows iis with

$_server['script_name']
jameslporter at gmail dot com
06-may-2006 03:19
refer to canonicalname if you are not getting the servername in the $_server[server_name] variable....this was a pain to figure out for me...now it works as expected by turning canonical naming on.

http://www.apacheref.com/ref/http_core/usecanonicalname.html
tchamp
26-apr-2006 10: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 09: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

// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc

$_real_script_dir = realpath(dirname($_server['script_filename'])); // filesystem path of this page's directory (page.php)
$_real_base_dir = realpath(dirname(__file__)); // filesystem path of this file's directory (config.php)
$_my_path_part = substr( $_real_script_dir, strlen($_real_base_dir)); // just the subfolder part between <installation_path> and the page

$installation_path = $_my_path_part
    ? substr( dirname($_server['script_name']), 0, -strlen($_my_path_part) )
    : dirname($_server['script_name'])
; // we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)

?>
todd dot kisov at yahoo dot com
03-apr-2006 05: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;
    }
01-apr-2006 01: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 05: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.
adam3000 at gmail dot com
16-mar-2006 02: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
08-mar-2006 05: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
01-mar-2006 04: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'], "http:///");

  
$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
23-feb-2006 12: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.
geza at turigeza dot com
11-feb-2006 09: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
(
)
marsh at nospam-takethatspammer dot uri
20-jan-2006 12: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
12-jan-2006 11: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 09:02
the following code is licensed under the gpl and it is from the gallery.menalto.com project.
<?php
    /**
     * fix the superglobal $_cookie to conform with rfc 2965
     *
     * we don't use $_cookie[$cookiename], because it doesn't conform to rfc 2965 (the
     * cookie standard), i.e. in $_cookie, we don't get the cookie with the most specific path for
     * a given cookie name, we get the cookie with the least specific cookie path.
     * this function does it exactly the other way around, to a) fix our cookie/login problems and
     * to b) conform with the rfc.
     * the php bug was already fixed in spring 2005, but we will have to deal with broken php
     * versions for a long time. see http://bugs.php.net/bug.php?id=32802.
     *
     * fixes also another php cookie bug. php doesn't expect the cookie header to have
     * quoted-strings, but they are perfectly legal according to rfc 2965.
     *
     * the third bug fixed here is an ms internet explorer (ie) bug. when using default cookie
     * domains (no leading dot, don't set the domain in set-cookie), ie is supposed to return only
     * cookies that have the exact request-host as their domain.
     * example: cookies stored in the browser with cookie domains: .example.com, .www.example.com,
     *          example.com, www.example.com
     *          the request-host is www.example.com. thus, ie should return all those cookies but
     *          the example.com cookie, because it's a default domain cookie and it doesn't match
     *          exactly the request-host. but ie returns the example.com cookie too.
     * as ms decided that it returns the cookie with the best domain-match first (unspecified in
     * rfc 2965), this wouldn't be a problem if php didn't select the last cookie in the
     * http_cookie header. but with fixcookievars(), this case is also fixed.
     *
     * this function reevaluates the http cookie header and populates $_cookie with the correct
     * cookies. we fix only non-array and non '[', ']' containing cookies for simplicity. to fix
     * our login problem, we'd have to fix only the gallerysid cookie anyway.
     *
     * @param boolean force the reevaluation of the http header string cookie
     * @param boolean unset static variable for testability
     */
    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
info at meshkaat dot com
06-dec-2005 09: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 11: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']);
   
    /* work out how many folders we are away from document_root
       by working out how many folders deep we are from the url.
       this isn't fool proof */
    $adjust = explode("/", $current_script);
    $adjust = count($adjust)-1;
   
    /* move up the path with ../ */
    $traverse = str_repeat("../", $adjust);
    $adjusted_path = sprintf("%s/%s", $current_path, $traverse);

    /* real path expands the ../'s to the correct folder names */
    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).
lorenpr at gmail dot com
02-nov-2005 07: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 11: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.
drew dot griffiths at clare dot net
30-sep-2005 11: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 06: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/";                                       // example: http://servername/profiles/search_string
$mplength = strlen( $mainpath  );                               
$request_uri = $_server['request_uri'];

if ( $mainpath != substr($request_uri,0,$mplength) ) {          // check if the given uri is valid
    echo "404 page not found !";
    exit();
}

$name = substr ($request_uri , $mplength ) ;                    // extract the string to be searched

echo "you have searched for the profile of mr. $name";

/** here you can write the code to retrieve and display
     the $name's  information from the database
*/
?>

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 11: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() {
// pick the predefined variable that works on your server
      return $_env['script_url'];
}
?>
or
<?php
// pick the predefined variable that works on your server
define("true_url_path", $_env['script_url']);
?>
gregory boshoff
31-jul-2005 05:41
$_server['query_string']

does not contain xhtml 1.1 compliant ampersands i.e. &amp;

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('&amp;', '&'), array('&', '&amp;'),
$_server['query_string']);
new york php
24-jul-2005 09:59
warning: $_server['php_self'] can include arbitrary user input. the documentation should be updated to reflect this.

the request "

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 11: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
16-jul-2005 02: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.
andy dot gajetzki at gmail dot com
06-jul-2005 09: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 10: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 09: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 04: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
14-jun-2005 04: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 09: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 03:12
also aviable is the $_server['server_addr'] which returns the current ip of the server the script is running on.
webkami (et) akdomains.com
24-may-2005 02: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.

<?

//for url variables
$req = new requestget();
echo "int:".$req->getvarint("id")."<br />";
echo "alpha:".$req->getvaralpha("name",4)."<br />";

//for form variables
$req = new requestpost();
echo "int:".$req->getvarint("id")."<br />";
echo "alpha:".$req->getvaralpha("name",4)."<br />";

//for cookies
$req = new requestcookie();
echo "int:".$req->getvarint("id")."<br />";
echo "alpha:".$req->getvaralpha("name",4)."<br />";

//for your own variables, set your values to an item in an array and you can modify the array

$filter["id"]=4;
$filter["name"]="ali";
$req = new requestfilter($filter);
echo "int:".$req->getvarint("id")."<br />";
echo "alpha:".$req->getvaralpha("name",4)."<br />";

?>
jm
18-may-2005 04:08
the $_server['php_auth_*'] variables are not available in safe mode.  see http://www.php.net/features.http-auth
www dot php dot net at webdevelopers dot cz
12-may-2005 09: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
07-may-2005 02: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 09: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
11-apr-2005 07: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);
    //extra code for making the languages key indexed
    $i = 0;
    $lang_index = array();
    foreach($lang_q as $lang => $q) {
    //    $lang_q[$i] = $lang; //add to the same array the index key/language
        $lang_index[$i] = $lang; //add to a new array the index key/language
        $i++;
    }
   
    //return $lang_index; // uncomment for returning array with keys={0..n-1}, values={most..least preferred}
    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
27-mar-2005 12:36
$_server["remote_user"] and $_server['php_auth_user'] is the same variable i think..
anonymous
04-mar-2005 06:12
i don't see the $_server["remote_user"] listed in this document.
this displays the username used to login using .htaccess.
28-feb-2005 10: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.
17-feb-2005 07: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
14-feb-2005 08: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
12-feb-2005 11: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
11-feb-2005 03: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 06: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
27-jan-2005 04: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
24-jan-2005 08:02
the variable $php_errormsg is not populated if you have xdebug running.
arjini at gmail dot com
19-jan-2005 08:29
driven crazy by the lack of consistency with $_server across installations? check out this chart:

http://www.koivi.com/apache-iis-php-server-array.php
roy dot rico at gmail dot com
19-jan-2005 05: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
10-jan-2005 05: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, ") {
  /* if so, use the backslash position instead */
  $intlastslash = strrpos($strscript, "http://");
 }

 /* 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
26-dec-2004 08:50
a reminder: if you are considering using urldecode() on a $_get variable, don't!

evil php:

<?php
# bad code! do not use!
$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 11: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 03: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 10: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 08:34
$_server['document_root'] *is* supported by iis, although only when running php as an isapi module.
youdontmeanmuch [at] yahoo.com
06-apr-2004 12: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
19-dec-2003 01: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
04-dec-20

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 铁力市| 景泰县| 蒙山县| 九龙城区| 新竹县| 上杭县| 镇平县| 荆州市| 镇坪县| 唐河县| 左贡县| 涡阳县| 葫芦岛市| 太原市| 东乌珠穆沁旗| 海宁市| 乌什县| 阿克陶县| 浮梁县| 临颍县| 武隆县| 丹寨县| 嘉鱼县| 清徐县| 临夏市| 轮台县| 海宁市| 新宁县| 易门县| 萝北县| 林西县| 崇明县| 宜阳县| 五家渠市| 武冈市| 崇仁县| 阳高县| 大理市| 密云县| 靖西县| 巴楚县|