将绝对/相对(本地)路径映射到绝对URL [英] Mapping Absolute / Relative (Local) Paths to Absolute URLs

查看:499
本文介绍了将绝对/相对(本地)路径映射到绝对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种快速可靠的方法来将绝对或相对的 local 路径(例如./images/Mafalda.jpg)映射到其对应的绝对URL,到目前为止,我已经设法解决了这个问题:

I need a fast and reliable way to map an absolute or relative local path (say ./images/Mafalda.jpg) to it's corresponding absolute URL, so far I've managed to come up with this:

function Path($path)
{
    if (file_exists($path) === true)
    {
        return rtrim(str_replace('\\', '/', realpath($path)), '/') . (is_dir($path) ? '/' : '');
    }

    return false;
}

function URL($path)
{
    $path = Path($path);

    if ($path !== false)
    {
        return str_replace($_SERVER['DOCUMENT_ROOT'], getservbyport($_SERVER['SERVER_PORT'], 'tcp') . '://' . $_SERVER['HTTP_HOST'], $path);
    }

    return false;
}

URL('./images/Mafalda.jpg'); // http://domain.com/images/Mafalda.jpg

似乎可以按预期工作,但是由于这是我的应用程序的一项关键功能,因此我想问问是否有人可以发现我可能错过的任何问题,并且也欢迎进行优化,因为我将多次使用此功能每个请求的次数.有人吗?

Seems to be working as expected, but since this is a critical feature to my app I want to ask if anyone can spot any problem that I might have missed and optimizations are also welcome since I'm going to use this function several times per each request. Anyone?

推荐答案

要注意的一个潜在问题是符号链接.如果DOCUMENT_ROOT包含符号链接的一部分,那么事情将会崩溃(因为realpath()将扩展该符号链接).

One potential issue to look out for is symbolic links. If DOCUMENT_ROOT contains a part that is a symlink, things will blow up (since realpath() will expand that symlink).

当然,解决方案也可能像将$ _SERVER ['DOCUMENT_ROOT']包裹在realpath()中一样简单.

Of course, the solution might be as simple as wrapping $_SERVER['DOCUMENT_ROOT'] in realpath() as well.

这篇关于将绝对/相对(本地)路径映射到绝对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆