如何使用 PHP 获取基本 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2820723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:45:54  来源:igfitidea点击:

How do I get the base URL with PHP?

php

提问by shin

I am using XAMPPon Windows Vista. In my development, I have http://127.0.0.1/test_website/.

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

How do I get http://127.0.0.1/test_website/with PHP?

我如何http://127.0.0.1/test_website/使用 PHP?

I tried something like these, but none of them worked.

我尝试过类似的方法,但都没有奏效。

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

回答by ma?ek

Try this:

尝试这个:

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

Learn more about the $_SERVERpredefined variable.

了解有关$_SERVER预定义变量的更多信息。

If you plan on using https, you can use this:

如果你打算使用 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

Per this answer, please make sure to configure your Apache properly so you can safely depend on SERVER_NAME.

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

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

NOTE: If you're depending on the HTTP_HOSTkey (which contains user input), you still have to make some cleanup, remove spaces, commas, carriage return, etc. Anything that is not a valid character for a domain. Check the PHP builtin parse_urlfunction for an example.

注意:如果您依赖于HTTP_HOST键(包含用户输入),您仍然需要进行一些清理、删除空格、逗号、回车等。任何对域来说不是有效字符的东西。以 PHP 内置的parse_url函数为例。

回答by ftrotter

Function adjusted to execute without warnings:

功能调整为在没有警告的情况下执行:

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'];
}

回答by SpYk3HH

Fun 'base_url' snippet!

有趣的“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;
    }
}

Use as simple as:

使用简单如:

//  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/"
//      }

回答by agravat.in

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

Its just simple to use
Output :

使用
Output很简单

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

回答by user3832931

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

Usage:

用法:

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

回答by Jeremy DeGroot

I think the $_SERVERsuperglobal has the information you're looking for. It might be something like this:

我认为$_SERVERsuperglobal 拥有您正在寻找的信息。它可能是这样的:

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

You can see the relevant PHP documentation here.

您可以在此处查看相关的 PHP 文档。

回答by rrsantos

Try the following code :

试试下面的代码:

$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'];

回答by Jijesh Cherrai

The following code will reduce the problem to check the protocol. The $_SERVER['APP_URL'] will display the domain name with the protocol

以下代码将减少检查协议的问题。$_SERVER['APP_URL'] 将显示带有协议的域名

$_SERVER['APP_URL'] will return protocol://domain( eg:-http://localhost)

$_SERVER['APP_URL'] 将返回protocol://domain(例如:- http://localhost

$_SERVER['REQUEST_URI'] for remaining parts of the url such as /directory/subdirectory/something/else

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

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

The output would be like this

输出将是这样的

http://localhost/directory/subdirectory/something/else

http://localhost/directory/subdirectory/something/else

回答by Hoàng V? Tgtt

I found this on http://webcheatsheet.com/php/get_current_page_url.php

我在http://webcheatsheet.com/php/get_current_page_url.php上找到了这个

Add the following code to a page:

将以下代码添加到页面:

<?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;
}
?>

You can now get the current page URL using the line:

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

<?php
  echo curPageURL();
?>

Sometimes it is needed to get the page name only. The following example shows how to do it:

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

<?php
function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}

echo "The current page name is ".curPageName();
?>

回答by Crazy SagaXxX

You can do it like this, but sorry my english is not good enough.

你可以这样做,但很抱歉我的英语不够好。

First, get home base url with this simple code..

首先,使用这个简单的代码获取家庭基地网址..

I've tested this code on my local server and public and the result is good.

我已经在本地服务器和公共服务器上测试了这段代码,结果很好。

<?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();

output will like this :

输出将是这样的:

local machine : http://localhost/my_website/ or https://myhost/my_website 

public : http://www.my_website.com/ or https://www.my_website.com/

use home_base_urlfunction at index.phpof your website and define it

使用您网站的home_base_url功能index.php并定义它

and then you can use this function to load scripts, css and content via url like

然后您可以使用此功能通过 url 加载脚本、css 和内容,例如

<?php

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

?>

will create output like this :

将创建这样的输出:

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

and if this script works fine,,!

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