2017-01-23 197 views
0

對於得到的圖像網址我使用的主要場所獲取URL路徑URL鏈接(PHP)

<a href="./index.html"><img src="./images/logo.png" class="" alt=""></a> 

但對於子網站,我需要用這個

<a href="../index.html"><img src="../images/logo.png" class="" alt=""></a> 

我怎麼能得到url網站使用PHP代碼爲此,因爲我想創建兩個PHP文件,頁眉和頁腳,我需要像獲取url網站的url鏈接,並應在兩個網站(主要和子)上工作。

我試圖用

<img src="<?php echo url('images/logo.png') ?>" alt=""> 

但圖像不顯示。

感謝

+1

同樣的邏輯可以檢出$ _ SERVER變量,要麼HTTP_HOST或PATH_INFO應該可以幫助你。 http://php.net/manual/en/reserved.variables.server.php – jbrahy

回答

0

如果您的域名是www.example.com,你可能想嘗試從REQUEST_URI that is $_SERVER['REQUEST_URI']

獲取所需的信息。例如:

function get_image_path($image) { 

    $parts = explode('/',$_SERVER['REQUEST_URI']); 
    $temp = array_shift($parts); 
    $image_path = ''; 
    foreach($parts as $part){ 
     $image_path.='../'; 
    } 
    return $image_path.$image; 
} 

用法:

print get_image_path('images/1.jpg'); 

這應該適用於www.example.com/script.php和w ww.example.com/sub/script.php(和嵌套任意數量的子文件夾或沒有)

用於URL($文件)功能

+0

Yeap它爲www.example.com工作很棒:)但是localhost呢?我使用本地主機作爲我的測試本地服務器,所以你的方法不在這裏工作。 – Lucas