php获取网站基础路径baseUrl的两种方法
本文发布于 11 年前, 内容可能已经过时或失效!
文章目录
php获取网站基础路径baseUrl的两种方法
方法一:
// baseUrl
function baseUrl($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
*/
function baseUrl(){
// 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']."/";
}
最后贴上:php获取当前页面完整url 的方法.