2010-05-12 123 views
93

我在Windows上使用XAMPP   Vista。在我的發展中,我有http://127.0.0.1/test_website/如何使用PHP獲取基本URL?

如何使用PHP獲得http://127.0.0.1/test_website/

我嘗試了類似這些,但沒有一個工作。

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

他們是如何工作的?他們回來了什麼? – animuson 2010-05-12 16:21:04

+5

@animuson那些常量返回本地文件系統路徑,而不是URL。 – ceejayoz 2010-05-12 16:27:16

+0

可能重複的[在PHP中獲取完整的URL](http://stackoverflow.com/questions/6768793/get-the-full-url-in-php) – 2014-11-27 20:13:34

回答

202

試試這個:

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

瞭解更多關於$_SERVER Predefined Variable

如果您計劃使用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 

this answer,請務必正確配置您的Apache,以便您可以安全地依賴於SERVER_NAME

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

注意:如果你根據HTTP_HOST鍵(其中包含用戶輸入),你仍然必須做出一些清理,刪除空格,逗號,回車,任何不是一個有效的字符一個域名。例如檢查php內建函數parse_url

+1

應該檢查'$ _SERVER ['HTTPS']'和在這些情況下,交換「https://」而不是「http://」。 – ceejayoz 2010-05-12 16:26:37

+0

@ceejayoz,包含此更新的答案。 – 2010-05-12 16:37:06

+0

要小心,在協議中,你必須添加「://」 – 2010-06-09 12:55:34

5

我覺得$_SERVER超全球有你正在尋找的信息。它可能是這樣的:

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

你可以看到相關的PHP文檔here

+0

這會持續重定向到同一頁面用戶現在。這要重定向到主頁?我在Apache,本地主機。php7 – Joey 2017-12-14 08:06:02

20

功能進行調整,而不警告執行:

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

我知道我做過這個,因爲某些原因,我不記得是怎麼回事,謝謝! – jphreak 2013-02-19 03:36:26

+0

我需要設置主頁圖像的頭像。其他頁面而不是家庭,他/她應該通過點擊標題圖像重定向到主頁。我怎樣才能做到這一點? – Joey 2017-12-14 08:04:37

18

玩轉 '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) "https://stackoverflow.com/questions/2820723/" 
//  } 
2

你可以像這樣

但對不起我的英語不夠好,

第一次回家的基本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/ 

使用home_base_url功能。您的網站的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> 

,如果這個腳本工作正常,,!

+1

請不要在您的答案中包含指向您網站的鏈接 – ChrisF 2014-02-12 10:56:26

0
$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? "https://" : "http://"; 

$url = $http . $_SERVER["SERVER_NAME"] . $_SERVER['REQUEST_URI']; 
7

我的回答是

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

用法:

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

我發現這對 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; 
} 
?> 

現在,您可以使用行獲取當前頁面網址:

<?php 
    echo curPageURL(); 
?> 

有時需要只獲取頁面的名稱。下面的示例演示如何做到這一點:

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

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

最終的答案:

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

,你會得到 像

lalala/tralala/something/ 
+0

此問答條目中有很多代碼屬於危險區域,尤其是因爲使用了PHP_SELF。 – hakre 2015-09-24 16:36:59

0
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; 

} 
0

這裏有一個我放在一起工作爲了我。它將返回一個包含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提供的答案的擴展。 (信貸,信貸到期。)

2

簡易竅門:

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

URL看起來是這樣的:http://example.com/folder/

2

下面的代碼將問題縮小到檢查協議。 的$ _SERVER [ 'APP_URL']將與協議顯示域名

$ _SERVER [ 'APP_URL']將返回協議://域(例如: - http://localhost

$ _SERVER [ 'REQUEST_URI']提供了URL的其餘部分如/目錄/子目錄/事/其他

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

輸出會是這樣

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

+1

而不是隻是粘貼一堆隨機的代碼,解釋你做了什麼以及爲什麼。這樣,OP和任何具有相同問題的未來讀者實際上可以從你的答案中學到一些東西,而不僅僅是複製/粘貼它,明天又問同樣的問題。 – Oldskool 2016-05-13 08:56:15

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

它只是簡單的使用
輸出:

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

在@ user3832931的答案編輯,包括服務器端口..

形成的網址像'https://localhost:8000/folder/'

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

試試這個。這個對我有用。

/*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> 
0

嘗試使用:$_SERVER['SERVER_NAME'];

我用它來呼應我的網站基本URL鏈接我的CSS。

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

希望這會有所幫助!

0

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