簡體   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