【问题标题】:Is there a PHP function that does the opposite of real_path?是否有与 real_path 相反的 PHP 函数?
【发布时间】:2011-09-11 10:57:50
【问题描述】:

在上传脚本中,我有

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

我将图像路径上传到数据库,因此字符串存储是真实路径(即 S:\sites\www\mysite\uploads\username\entries\2011\file.png)

是否有一个函数可以将该真实路径转换为“http://sitename/uploads...”

虽然实现起来并不难,但我想知道是否有内置的。我查看了文档,但找不到任何东西。

【问题讨论】:

  • 这将如何工作?十几个 URL 可以(并且经常会)映射到同一个物理文件。该函数会返回哪一个,它应该使用什么占卜魔法?

标签: php


【解决方案1】:

即使有,它也不应该被认为是可靠的,因为 URL 中的组件不一定映射到文件系统中的路径。最好从路径中删除已知前缀,并将其替换为包含媒体的基本 URL。

【讨论】:

    【解决方案2】:

    我找到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));
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      看起来你需要做的就是以不同的方式构建你的路径。

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

      【讨论】:

        【解决方案4】:

        当然有。它被称为“替换路径”。即:

        $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']在那里添加您的域名。

        另一方面,您应该知道(符号)链接是多对一的。也就是说,您可能有多个指向同一个文件的快捷方式,但反之则不然。因此,您无法知道哪个快捷方式是正确的。

        【讨论】:

          【解决方案5】:

          “最靠谱”(慎用)是使用DIRECTORY_SEPARATOR

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

          【讨论】:

            猜你喜欢
            • 2016-10-15
            • 1970-01-01
            • 1970-01-01
            • 2014-09-08
            • 1970-01-01
            • 2023-03-07
            • 2012-09-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多