开发者

Is there a PHP function that does the opposite of real_path?

In an upload script, I have

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

and i upload the image path to the database, and thus the string stores is the real_path(ie. S:\sites\www\mysite\uploads\username\entries\2011\file.png)

is there a function that converts that real path into "http://sitename/uploads..."

althought not hard to implement, i was wondering if there is a built-in one. i looked in the docs but couldn't find an开发者_Go百科ything.


Even if there were, it shouldn't be considered reliable since components in the URL don't necessarily map to paths in the filesystem. Best to remove a known prefix from the path and replace it with a base URL containing the media.


I found 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));
}
?>


Looks like all you need to do is build your path differently.

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


Sure there is. It's called "replacing the path". Namely:

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

You can add your domain name there with $_SERVER['SERVER_NAME'].

On the other hand, you should know that (sym)links are many to one. That is, you may have several shortcuts pointing at the same file, but not vice-versa. As such, you can't know which shortcut is the right one.


The "most reliable" (consume with caution) is to use DIRECTORY_SEPARATOR:

$uri = str_replace( DIRECTORY_SEPARATOR, "/", ltrim( $path, $root ) )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜