获得url的详细信息

php有个预定义变量 $_SERVER,是个数组,其中包含了很多信息,遍历这个数组便可以找到我们感兴趣的东西。

function getRequestInfo() 
{
    foreach($_SERVER as $key => $value)
    {
        $key_html = '<span style="color:red">'.$key.'</span>';
        $value_html = '<span style="color:blue">'.$value.'</span>';
        echo $key_html.' => '.$value_html.'<br>';
    }
}


这里打印了很多信息,我们需要的是url相关的,先来看看url包含哪些组成部分。

<URL的访问方式>://<主机>:<端口>/<路径>

URL的访问方式有:

  1.ftp —— 文件传送协议 FTP

  2.http —— 超文本传送协议 HTTP

  3.News —— USENET 新闻

<主机> 是存放资源的主机在因特网中的域名

 

在地址栏写入:"http://localhost/index.php"

对号入座:

访问方式 => key: "SERVER_PROTOCOL",value: "HTTP/1.1"

  主机 => key: "SERVER_NAME",value: "localhost"

  端口 => key: "SERVER_PORT",value: "80"

  路径 => key: "REQUEST_URI",value:"/index.php" (待定,后面细说)


注意以下几点:

1. 端口是80时,HTTP_HOST = SERVER_NAME;

   端口不是80时,HTTP_HOST  = SERVER_NAME + SERVER_PORT;


2. 多数情况下,PHP_SELF, SCRIPT_NAME, REQUEST_URI 的值相等,区别如下:

$_SERVER['PHP_SELF']
http://www.yoursite.com/example/ — – — /example/index.php
http://www.yoursite.com/example/index.php — – — /example/index.php
http://www.yoursite.com/example/index.php?a=test — – — /example/index.php
http://www.yoursite.com/example/index.php/dir/test — – — /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/ — – — /example/index.php
http://www.yoursite.com/example/index.php — – — /example/index.php
http://www.yoursite.com/example/index.php — – — /example/index.php
http://www.yoursite.com/example/index.php/dir/test — – — /example/index.php
在所有的返回中都是当前的文件名/example/index.php


[路径] 应该域名后面的东西,如/example/index.php?a=test,但是呢,?后面的东西可以通过 $_SERVER['QUERY_STRING'] 或 $_GET 数组获得,所以这部分可以不用处理,我们的目的是拿到?前面的部分。


详细对比上面三个的值,我个人觉得用 REQUEST_URI 比较好,可以灵活地进行任何处理。

posted @ 2012-02-26 18:25  越己  阅读(238)  评论(0编辑  收藏  举报