關於$_SERVER中的PHP_SELF、REQUEST_URI以及SCRIPT_NAME的區別

文章主要引用於:https://www.cnblogs.com/zcy_soft/archive/2010/10/16/1853239.html

1.實驗環境:需要開啓appache的rewrite功能,在工程下創建index.php文件,然後在該工程下增加.htaccess文件——以單一入口文件形式訪問。

2.說明:現在很多站點都會引用單一入口原則,所以這是在單一入口基礎上得到的結果。

其中以四種不同的URL形式來訪問

http://www.yoursite.com/example/ 

http://www.yoursite.com/example/index.php 

http://www.yoursite.com/example/index.php?a=test

http://www.yoursite.com/example/index.php/dir/test

以下爲幾種不同結果和引用文得到的結果不同這是實驗環境不同不同所致的,請不要說誰錯了。引文其實也沒錯只是沒有說是什麼環境下可以得那樣的結果。好了直接給結果

3.結果:

$_SERVER[’PHP_SELF’]

  • http://www.yoursite.com/example/ — – — /index.php/example/index.php
  • http://www.yoursite.com/example/index.php — – — /index.php/example/index.php
  • http://www.yoursite.com/example/index.php?a=test — – — /index.php/example/index.php
  • http://www.yoursite.com/example/index.php/dir/test — – — /index.php/example/index.php/dir/test

當我們使用$_SERVER['PHP_SELF']的時候,無論訪問的URL地址是否有index.php,它都會自動的返回 index.php.但是如果在文件名後面再加斜線的話,就會把後面所有的內容都返回在$_SERVER['PHP_SELF']。

$_SERVER['REQUEST_URI']

  • http://www.yoursite.com/example/ — – — /example
  • http://www.yoursite.com/example/index.php — – — /example/index.php
  • http://www.yoursite.com/example/index.php?a=test — – — /example/index.php?a=test
  • http://www.yoursite.com/example/index.php/dir/test — – — /example/index.php/dir/test

$_SERVER['REQUEST_URI']返回的是我們在URL裏寫的精確的地址,如果URL只寫到”/”,就返回 “/”

$_SERVER['SCRIPT_NAME']

  • http://www.yoursite.com/example/ — – — /index.php
  • http://www.yoursite.com/example/index.php — – — /index.php
  • http://www.yoursite.com/example/index.php — – — /index.php
  • http://www.yoursite.com/example/index.php/dir/test — – — /index.php

在所有的返回中都是當前的文件名/example/index.php

4總結:在以上結果中REQUEST_URI是 HOST後面的內容。SCRIPT_NAME總是訪問的文件(再者即index.php),PHP_SELF則執行文件後面再接上URL路徑。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章