Answers:
试试这个:
<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>
了解有关$_SERVER
预定义变量的更多信息。
如果计划使用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
根据此答案,请确保正确配置Apache,以便您可以放心使用SERVER_NAME
。
<VirtualHost *>
ServerName example.com
UseCanonicalName on
</VirtualHost>
注意:如果您依赖于HTTP_HOST
键(包含用户输入),则仍必须进行一些清理,删除空格,逗号,回车符等。对于域不是有效字符的任何内容。查看PHP内置的parse_url函数以获取示例。
$_SERVER['HTTPS']
并更换,https://
而不是http://
在那种情况下。
调整功能以在没有警告的情况下执行:
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/"
// }
$modifyUrl = parse_url($url);
print_r($modifyUrl)
使用
Output 只是简单而已:
Array
(
[scheme] => http
[host] => aaa.bbb.com
[path] => /
)
https://example.com
从https://example.com/category2/page2.html?q=2#lorem-ipsum
-这无关与当前页你在。
试试下面的代码:
$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];
以下代码将减少检查协议的问题。$ _SERVER ['APP_URL']将显示带有协议的域名
$ _SERVER ['APP_URL']将返回协议://域(例如:-http:// localhost)
$ _SERVER ['REQUEST_URI']用于url的其余部分,例如/ directory / subdirectory / something / else
$url = $_SERVER['APP_URL'].$_SERVER['REQUEST_URI'];
输出将是这样的
http:// localhost / directory / subdirectory / something / else
我在http://webcheatsheet.com/php/get_current_page_url.php上 找到了
将以下代码添加到页面:
<?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();
?>
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];
试试这个。这个对我有用。
/*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>
简单的把戏:
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$baseurl = "http://" . $host . $path . "/";
URL看起来像这样: http://example.com/folder/
您可以这样做,但对不起,我的英语还不够好。
首先,使用此简单代码获取家庭基本网址。
我已经在本地服务器和公共服务器上测试了此代码,结果很好。
<?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/
home_base_url
在index.php
您的网站上使用功能并对其进行定义
然后您可以使用此功能通过url这样加载脚本,css和内容
<?php
echo '<script type="text/javascript" src="'.home_base_url().'js/script.js"></script>'."\n";
?>
将创建这样的输出:
<script type="text/javascript" src="http://www.my_website.com/js/script.js"></script>
如果此脚本可以正常运行,!
我刚刚整理了一个对我有用的东西。它将返回一个包含2个元素的数组。第一个元素是?之前的所有内容。第二个是一个包含关联数组中所有查询字符串变量的数组。
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提供的答案的扩展。(应贷方贷方。)
在@ user3832931的答案中进行了编辑,以包含服务器端口。
形成类似“ https:// localhost:8000 / folder / ”的URL
$base_url="http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].dirname($_SERVER["REQUEST_URI"].'?').'/';
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;
}
我有与OP相同的问题,但可能有不同的要求。我创建了这个功能...
/**
* 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;
}
...顺便说一句,我用它来帮助创建应用于重定向的绝对URL。
$some_variable = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['REQUEST_URI'], "/")+1);
你会得到类似
lalala/tralala/something/
只需测试并获得结果。
// 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/
echo $protocol.$hostName.$pathInfo['dirname']."/";
就我而言,我需要类似于文件中RewriteBase
包含的基本URL .htaccess
。
不幸RewriteBase
的.htaccess
是,用PHP不可能简单地从文件中检索。但是有可能在.htaccess文件中设置环境变量,然后在PHP中检索该变量。只需检查以下代码:
.htaccess
SetEnv BASE_PATH /
index.php
现在,我在模板的基础标签中使用此标签(在页面的头部):
<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>
因此,如果变量不为空,则使用它。否则回退到/
默认的基本路径。
根据环境,基本URL将始终是正确的。我使用/
本地和生产网站上的基本网址。但/foldername/
要针对暂存环境。
.htaccess
因为RewriteBase是不同的,所以它们都拥有自己的位置。所以这个解决方案对我有用。
看看$ _SERVER ['REQUEST_URI'],即
$current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
如果要同时支持HTTP和HTTPS,则可以使用此解决方案
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
这对我有用。希望对您有帮助。感谢您提出这个问题。