PHP中获取当前页面的完整URL
2017-04-03 17:46
736 查看
javascript实现
top.location.href 顶级窗口的地址 this.location.href 当前窗口的地址
PHP实现
#测试网址: http://localhost/blog/testurl.php?id=5 //获取域名或主机地址 echo $_SERVER['HTTP_HOST']."<br>"; #localhost //获取网页地址 echo $_SERVER['PHP_SELF']."<br>"; #/blog/testurl.php //获取网址参数 echo $_SERVER["QUERY_STRING"]."<br>"; #id=5 //获取用户代理 echo $_SERVER['HTTP_REFERER']."<br>"; //获取完整的url echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']; #http://localhost/blog/testurl.php?id=5 //包含端口号的完整url echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; #http://localhost:80/blog/testurl.php?id=5 //只取路径 $url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; echo dirname($url); #http://localhost/blog
举个例子
<?php $url = "web.safe.com/index.php?r=x/y#z"; //$url = $_SERVER['QUERY_STRING']; $parse = parse_url($url); if(isset($parse["fragment"])){ //parse_str($parse['query'],$params); var_dump($parse); } ?>
运行结果
array(3) { ["path"]=> string(22) "web.safe.com/index.php" ["query"]=> string(5) "r=x/y" ["fragment"]=> string(1) "z" }
其中parse_str()函数用法
<?php parse_str("name=Bill&age=60"); echo $name."<br>"; echo $age; ?>
输出
Bill 60
$_SERVER使用
第一种、利用$_SERVER内置数组变量
相对较为原始的
$_SERVER['QUERY_STRING']来获取,URL的参数,通常使用这个变量返回的会是类似这样的数据:
name=tank&sex=1
如果需要包含文件名的话可以使用
$_SERVER["REQUEST_URI"](返回类似:/index.php?name=tank&sex=1)
第二种、利用pathinfo内置函数
代码如下:
<?php $test = pathinfo("http://localhost/index.php"); print_r($test); /* 结果如下 Array ( [dirname] => http://localhost //url的路径 [basename] => index.php //完整文件名 [extension] => php //文件名后缀 [filename] => index //文件名 ) */ ?>
第三种、利用parse_url内置函数
代码如下:
<?php $test = parse_url("http://localhost/index.php?name=tank&sex=1#top"); print_r($test); /* 结果如下 Array ( [scheme] => http //使用什么协议 [host] => localhost //主机名 [path] => /index.php //路径 [query] => name=tank&sex=1 // 所传的参数 [fragment] => top //后面根的锚点 ) */ ?>
第四种、利用basename内置函数
代码如下:
<?php $test = basename("http://localhost/index.php?name=tank&sex=1#top"); echo $test; /* 结果如下 index.php?name=tank&sex=1#top */ ?>
另外,还有就是自己通过正则匹配的处理方式来获取需要的值了。这种方式较为精确,效率暂不考虑。。。
下面拓展实践下正则处理方式:
代码如下:
<?php preg_match_all("/(\w+=\w+)(#\w+)?/i","http://localhost/index.php?name=tank&sex=1#top",$match); print_r($match); /* 结果如下 Array ( [0] => Array ( [0] => name=tank [1] => sex=1#top ) [1] => Array ( [0] => name=tank [1] => sex=1 ) [2] => Array ( [0] => [1] => #top ) ) */ ?>
相关文章推荐
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP获取 当前页面名称、主机名、URL完整地址、URL参数、获取IP
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- php获取当前页面完整url
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP中获取当前页面的完整URL
- PHP获取当前页面完整URL的实现代码