繁体   English   中英

如何使用 PHP 获取基数 URL?

[英]How do I get the base URL with PHP?

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

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

我尝试过类似的方法,但没有一个起作用。

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

尝试这个:

<?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函数以获取示例。

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

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'/>";
$modifyUrl = parse_url($url);
print_r($modifyUrl)

它使用起来很简单
输出 :

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

我认为$_SERVER超全局具有您正在寻找的信息。 它可能是这样的:

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

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

试试下面的代码:

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

第一行是检查您的基本 url 是使用 http 还是 https,然后第二行用于获取主机名。然后第三行用于仅获取站点 ex 的基本文件夹。 /test_website/

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

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

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

<?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函数并定义它

然后您可以使用此功能通过 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>

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

以下代码将减少检查协议的问题。 $_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/子目录​​/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();
?>

简单易行的技巧:

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

URL 如下所示: http://example.com/folder/ ://example.com/folder/

$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>

这是我认为最好的方法。

$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);

echo $base_url;

这是我刚刚整理的一个对我有用的。 它将返回一个包含 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"].'?').'/';
$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;

}

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

我用它来回显我网站的基本 url 以链接我的 css。

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

希望这可以帮助!

我和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。

只需测试并获得结果。

// 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']."/";

就我而言,我需要类似于.htaccess文件中包含的RewriteBase的基本 URL。

不幸的是,简单地从.htaccess文件中检索RewriteBase是不可能使用 PHP 的。 但是可以在 .htaccess 文件中设置一个环境变量,然后在 PHP 中检索该变量。 只需检查这些代码:

.htaccess

SetEnv BASE_PATH /

索引.php

现在我在模板的基本标记中使用它(在页面的头部):

<base href="<?php echo ! empty( getenv( 'BASE_PATH' ) ) ? getenv( 'BASE_PATH' ) : '/'; ?>"/>

所以如果变量不为空,我们就使用它。 否则回退到/作为默认基本路径。

根据环境,基本 URL 将始终正确。 我在本地和生产网站上使用/作为基本 url。 但是/foldername/用于暂存环境。

首先,它们都有自己的.htaccess ,因为 RewriteBase 不同。 所以这个解决方案对我有用。

$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://";
$dir =  str_replace(basename($_SERVER['SCRIPT_NAME']), '',$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']);
echo $url = $http . $dir;
// echo $url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI'];

即使当前 url 具有请求查询字符串,以下解决方案也将起作用。

<?php 

function baseUrl($file=__FILE__){
    $currentFile = array_reverse(explode(DIRECTORY_SEPARATOR,$file))[0];
    if(!empty($_SERVER['QUERY_STRING'])){
        $currentFile.='?'.$_SERVER['QUERY_STRING'];
    }
    $protocol = $_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) &&     
                              !empty($_SERVER['HTTPS']) ? 'https' : 'http';
    $url = "$protocol://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $url = str_replace($currentFile, '', $url);

    return $url;
}

调用文件将提供__FILE__作为参数

<?= baseUrl(__FILE__)?>

目前这是正确的答案:

$baseUrl = $_SERVER['REQUEST_SCHEME'];
$baseUrl .= '://'.$_SERVER['HTTP_HOST'];

您可能想在末尾添加一个/ 或者你可能想添加

$baseUrl .= $_SERVER['REQUEST_URI'];

所以总共复制粘贴

$baseUrl = $_SERVER['REQUEST_SCHEME']
    . '://' . $_SERVER['HTTP_HOST']
    . $_SERVER['REQUEST_URI'];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM