2011-06-09 38 views
2

在上傳腳本,我有是否有一個與real_path相反的PHP函數?

$destination = $_SERVER['DOCUMENT_ROOT'] . '/uploads/'. $_SESSION['username'] . '/entries/' . '/' . $year . '/'; 

和我上傳的圖片數據庫路徑,因此,串店是REAL_PATH(即S:\網站\ WWW \ mysite的\上傳\用戶名\項\ 2011 \ file.png)

是有沒有真正的路徑轉換爲功能的「http://站點名稱/上傳...」

althought並不難實現,我想知道是否有一個內置的。我查看了文檔,但找不到任何東西。

+2

如何將這項工作?十幾個URL可以(並且經常會)映射到相同的物理文件。哪一個函數會返回,以及它應該使用什麼占卜魔法? – Damon 2011-06-09 06:53:18

回答

2

看起來所有你需要做的是建立你的路徑不同。

$base = '/uploads/'. $_SESSION['username'] . '/entries/' . '/' . $year . '/'; 
$destination = $_SERVER['DOCUMENT_ROOT'] . $base; 
$url = $_SERVER['HTTP_HOST'] . $base; 
5

即使存在,也不應將其視爲可靠,因爲URL中的組件不一定映射到文件系統中的路徑。最好從路徑中移除一個已知的前綴,並將其替換爲包含媒體的基本URL。

3

我發現this one at php.net

<?php 
function mapURL($relPath) { //This function is not perfect, but you can use it to convert a relative path to a URL. Please email me if you can make any improvements. 

    $filePathName = realpath($relPath); 
    $filePath = realpath(dirname($relPath)); 
    $basePath = realpath($_SERVER['DOCUMENT_ROOT']); 

    // can not create URL for directory lower than DOCUMENT_ROOT 
    if (strlen($basePath) > strlen($filePath)) { 
     return ''; 
    } 

    return 'http://' . $_SERVER['HTTP_HOST'] . substr($filePathName, strlen($basePath)); 
} 
?> 
1

肯定有。它被稱爲「替代路徑」。即:

$file = 'S:\\sites\\www\\mysite\\uploads\\username\\entries\\2011\\file.png'; 

$root = 'S:\\sites\\www\\mysite\\'; 

$web = str_replace(array($root,'\\'), array('/','/'), $file); 

$web => '/uploads/username/entries/2011/file.png' 

您可以在那裏添加您的域名$_SERVER['SERVER_NAME']

另一方面,你應該知道(sym)鏈接是多對一的。也就是說,您可能有幾個快捷方式指向同一個文件,但反之亦然。因此,你無法知道哪個捷徑是正確的。

1

的 「最可靠」(謹慎消費)是使用DIRECTORY_SEPARATOR

$uri = str_replace(DIRECTORY_SEPARATOR, "/", ltrim($path, $root)) 
相關問題