如何使用PHP获取基本URL?

我在Windows Vista上使用XAMPP 。 在我的开发中,我有http://127.0.0.1/test_website/

如何使用PHP获取http://127.0.0.1/test_website/

我试过这样的东西,但都没有工作。

 echo dirname(__FILE__) or echo basename(__FILE__); etc. 

尝试这个:

 <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?> 

了解有关$_SERVER预定义variables的更多信息

如果你打算使用https,你可以使用这个:

 function url(){ return sprintf( "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI'] ); } echo url(); #=> http://127.0.0.1/foo 

根据这个答案 ,请确保正确configuration您的Apache,以便您可以安全地依赖于SERVER_NAME

 <VirtualHost *> ServerName example.com UseCanonicalName on </VirtualHost> 

注意 :如果你依赖的HTTP_HOST键(包含用户input),你仍然需要做一些清理,删除空格,逗号,回车,任何不是一个域的有效字符。 检查php内置parse_url函数的例子。

function调整为无警告执行:

 function url(){ if(isset($_SERVER['HTTPS'])){ $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http"; } else{ $protocol = 'http'; } return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; } 

有趣的“base_url”片段!

 if (!function_exists('base_url')) { function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){ if (isset($_SERVER['HTTP_HOST'])) { $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http'; $hostname = $_SERVER['HTTP_HOST']; $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']); $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY); $core = $core[0]; $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s"); $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir); $base_url = sprintf( $tmplt, $http, $hostname, $end ); } else $base_url = 'http://localhost/'; if ($parse) { $base_url = parse_url($base_url); if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = ''; } return $base_url; } } 

使用如下简单:

 // url like: http://stackoverflow.com/questions/2820723/how-to-get-base-url-with-php echo base_url(); // will produce something like: http://stackoverflow.com/questions/2820723/ echo base_url(TRUE); // will produce something like: http://stackoverflow.com/ echo base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); // will produce something like: http://stackoverflow.com/questions/ // and finally echo base_url(NULL, NULL, TRUE); // will produce something like: // array(3) { // ["scheme"]=> // string(4) "http" // ["host"]=> // string(12) "stackoverflow.com" // ["path"]=> // string(35) "/questions/2820723/" // } 

我的答案是

 $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/'; 

用法:

 print "<script src='{$base_url}js/jquery.min.js'/>"; 

我觉得$_SERVER超全球有你正在寻找的信息。 这可能是这样的:

 echo $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] 

你可以在这里看到相关的PHP文档。

 $modifyUrl = parse_url($url); print_r($modifyUrl) 

它只是简单的使用
输出:

 Array ( [scheme] => http [host] => aaa.bbb.com [path] => / ) 

你可以这样做

但对不起,我的英文不够好,

首先用这个简单的代码获得家庭基地的url..

我已经通过本地服务器和公共testing这个代码,结果是好的..

 <?php function home_base_url(){ // first get http protocol if http or https $base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']!='off') ? 'https://' : 'http://'; // get default website root directory $tmpURL = dirname(__FILE__); // when use dirname(__FILE__) will return value like this "C:\xampp\htdocs\my_website", //convert value to http url use string replace, // replace any backslashes to slash in this case use chr value "92" $tmpURL = str_replace(chr(92),'/',$tmpURL); // now replace any same string in $tmpURL value to null or '' // and will return value like /localhost/my_website/ or just /my_website/ $tmpURL = str_replace($_SERVER['DOCUMENT_ROOT'],'',$tmpURL); // delete any slash character in first and last of value $tmpURL = ltrim($tmpURL,'/'); $tmpURL = rtrim($tmpURL, '/'); // check again if we find any slash string in value then we can assume its local machine if (strpos($tmpURL,'/')){ // explode that value and take only first value $tmpURL = explode('/',$tmpURL); $tmpURL = $tmpURL[0]; } // now last steps // assign protocol in first value if ($tmpURL !== $_SERVER['HTTP_HOST']) // if protocol its http then like this $base_url .= $_SERVER['HTTP_HOST'].'/'.$tmpURL.'/'; else // else if protocol is https $base_url .= $tmpURL.'/'; // give return value return $base_url; } ?> // and test it echo home_base_url(); 

输出将如下所示:

 local machine : http://localhost/my_website/ or https://myhost/my_website public : http://www.my_website.com/ or https://www.my_website.com/ 

在你的网站的index.php上使用home_base_url函数并定义它

然后你可以使用这个函数来加载脚本,CSS和内容通过url

 <?php echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n"; ?> 

会创build这样的输出:

 <script type="text/javascript" src="http://www.my_website.com/js/script.js"></script> 

如果这个脚本工作正常,!

简单而简单的把戏:

 $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); $path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); $baseurl = "http://" . $host . $path "/"; 

url如下所示: http : //domain.com/folder/

下面的代码将减less检查协议的问题。 $ _SERVER ['APP_URL']将显示协议的域名

$ _SERVER ['APP_URL']将返回协议:/ /域 (例如: – http://本地主机 )

$ _SERVER ['REQUEST_URI']用于url的其他部分,例如/ directory / subdirectory / something / else

  $url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI']; 

输出将是这样的

HTTP://本地主机/目录/子目录/事/其他

尝试这个。 这个对我有用。

 /*url.php file*/ trait URL { private $url = ''; private $current_url = ''; public $get = ''; function __construct() { $this->url = $_SERVER['SERVER_NAME']; $this->current_url = $_SERVER['REQUEST_URI']; $clean_server = str_replace('', $this->url, $this->current_url); $clean_server = explode('/', $clean_server); $this->get = array('base_url' => "/".$clean_server[1]); } } 

像这样使用:

 <?php /* Test file Tested for links: http://localhost/index.php http://localhost/ http://localhost/index.php/ http://localhost/url/index.php http://localhost/url/index.php/ http://localhost/url/ab http://localhost/url/ab/c */ require_once 'sys/url.php'; class Home { use URL; } $h = new Home(); ?> <a href="<?=$h->get['base_url']?>">Base</a> 

我在http://webcheatsheet.com/php/get_current_page_url.php上find了这个;

将下面的代码添加到页面中:

 <?php function curPageURL() { $pageURL = 'http'; if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } ?> 

您现在可以使用以下行获取当前页面的URL:

 <?php echo curPageURL(); ?> 

有时只需要获取页面名称。 以下示例显示如何执行此操作:

 <?php function curPageName() { return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); } echo "The current page name is ".curPageName(); ?> 

编辑在@ user3832931的答案包括服务器端口..

形成像“ https:// localhost:8000 / folder / ”这样的URL

 $base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/'; 
 $http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://"; $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']; 

最终答案:

 $some_variable = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1); 

你会得到类似的东西

 lalala/tralala/something/ 
 function server_url(){ $server =""; if(isset($_SERVER['SERVER_NAME'])){ $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], '/'); } else{ $server = sprintf("%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_ADDR'], '/'); } print $server; } 

这里有一个我只是放在一起,这对我有用。 它将返回一个包含2个元素的数组。 第一个元素是之前的一切? 第二个是包含关联数组中所有查询stringvariables的数组。

 function disectURL() { $arr = array(); $a = explode('?',sprintf( "%s://%s%s", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME'], $_SERVER['REQUEST_URI'] )); $arr['base_url'] = $a[0]; $arr['query_string'] = []; if(sizeof($a) == 2) { $b = explode('&', $a[1]); $qs = array(); foreach ($b as $c) { $d = explode('=', $c); $qs[$d[0]] = $d[1]; } $arr['query_string'] = (count($qs)) ? $qs : ''; } return $arr; } 

注意:这是由maček提供的答案的扩展。 (信贷到期时的信用)

尝试使用: $_SERVER['SERVER_NAME'];

我用它来回应我的网站的基础链接来链接我的CSS。

 <link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/assets/css/your-stylesheet.css" rel="stylesheet" type="text/css"> 

希望这可以帮助!

我和OP有同样的问题,但也许有不同的要求。 我创build了这个function…

 /** * Get the base URL of the current page. For example, if the current page URL is * "https://example.com/dir/example.php?whatever" this function will return * "https://example.com/dir/" . * * @return string The base URL of the current page. */ function get_base_url() { $protocol = filter_input(INPUT_SERVER, 'HTTPS'); if (empty($protocol)) { $protocol = "http"; } $host = filter_input(INPUT_SERVER, 'HTTP_HOST'); $request_uri_full = filter_input(INPUT_SERVER, 'REQUEST_URI'); $last_slash_pos = strrpos($request_uri_full, "/"); if ($last_slash_pos === FALSE) { $request_uri_sub = $request_uri_full; } else { $request_uri_sub = substr($request_uri_full, 0, $last_slash_pos + 1); } return $protocol . "://" . $host . $request_uri_sub; } 

…顺便说一句,我用它来帮助创build绝对的URL,用于redirect。