在php中我们要获取 当前页面完整url地址需要使用到几个常用的php全局变量函数了,主要是以$_SERVER[]这些变量,下面我来给各位看一个获取当前页面完整url地址程序吧。
先来看一些PHP变量:
$_SERVER[ 'SERVER_NAME' ] #当前运行脚本所在服务器主机的名称。
$_SERVER[ 'QUERY_STRING' ] #查询(query)的字符串。
$_SERVER[ 'HTTP_HOST' ] #当前请求的 Host: 头部的内容。
$_SERVER[ 'HTTP_REFERER' ] #链接到当前页面的前一页面的 URL 地址。
$_SERVER[ 'SERVER_PORT' ] #服务器所使用的端口
$_SERVER[ 'REQUEST_URI' ] #访问此页面所需的 URI。
有了些面函数我们就可以开始了,先来看一些base方法.
baseUrl的两种方法
方法一代码如下:
// baseUrl
functionbaseUrl($uri=''){
$baseUrl= ( isset($_SERVER['HTTPS']) &&$_SERVER['HTTPS'] !='off') ?'https://':'http://';
$baseUrl.= isset($_SERVER['HTTP_HOST']) ?$_SERVER['HTTP_HOST'] :getenv('HTTP_HOST');
$baseUrl.= isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : dirname(getenv('SCRIPT_NAME'));
return$baseUrl.'/'.$uri;
}
方法二代码如下:
/**
* Suppose, you are browsing in your localhost
* http://localhost/myproject/index.php?id=8
*/
functionbaseUrl()
{
// output: /myproject/index.php
$currentPath=$_SERVER['PHP_SELF'];
// output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
$pathInfo=pathinfo($currentPath);
// output: localhost
$hostName=$_SERVER['HTTP_HOST'];
// output: http://
$protocol=strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https://'?'https://':'http://';
// return: http://localhost/myproject/
return$protocol.$hostName.$pathInfo['dirname']."/";
}
方法三代码如下:
/**
*@author mckee
*@blog http://www.vcphp.com
*/
functionget_page_url(){
$url= (isset($_SERVER['SERVER_PORT']) &&$_SERVER['SERVER_PORT'] =='443') ?'https://':'http://';
$url.=$_SERVER['HTTP_HOST'];
$url.= isset($_SERVER['REQUEST_URI']) ?$_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) .'?'. urlencode($_SERVER['QUERY_STRING']);
return$url;
}
echoget_page_url();
?>
下面说明一下获取当前页面完整路径的方法,代码如下:
functiongetFullUrl(){
# 解决通用问题
$requestUri='';
if(isset($_SERVER['REQUEST_URI'])) { #$_SERVER["REQUEST_URI"] 只有 apache 才支持,
$requestUri=$_SERVER['REQUEST_URI'];
} else{
if(isset($_SERVER['argv'])) {
$requestUri=$_SERVER['PHP_SELF'] .'?'.$_SERVER['argv'][0];
} elseif(isset($_SERVER['QUERY_STRING'])) {
$requestUri=$_SERVER['PHP_SELF'] .'?'.$_SERVER['QUERY_STRING'];
}
}
// echo $requestUri.'
';
$scheme=emptyempty($_SERVER["HTTPS"]) ?'': ($_SERVER["HTTPS"] =="on") ?"s":"";
$protocol=strstr(strtolower($_SERVER["SERVER_PROTOCOL"]),"/",true) .$scheme;
$port= ($_SERVER["SERVER_PORT"] =="80") ?"": (":".$_SERVER["SERVER_PORT"]);
# 获取的完整url
$_fullUrl=$protocol."://".$_SERVER['SERVER_NAME'] .$port.$requestUri;
return$_fullUrl;
}
echo getFullUrl();注:由于php没有内置的函数,我们需要对url上的参数进行组合,从而实现整个url.
(责任编辑:admin)