PHP - 将文件系统路径转换为URL

Xeo*_*oss 27 php filesystems url

我经常发现我的项目中有文件需要从文件系统和用户浏览器访问.一个例子是上传照片.我需要访问文件系统上的文件,以便我可以使用GD来改变图像或移动它们.但我的用户还需要能够从URL访问文件example.com/uploads/myphoto.jpg.

因为上传路径通常对应于我构成了一个似乎在大多数时间都可以工作的函数的URL.以这些路径为例:

文件系统/var/www/example.com/uploads/myphoto.jpg

网址 http://example.com/uploads/myphoto.jpg

如果我将变量设置为类似的东西,/var/www/example.com/我可以从文件系统路径中减去它,然后将其用作图像的URL.

/**
 * Remove a given file system path from the file/path string.
 * If the file/path does not contain the given path - return FALSE.
 * @param   string  $file
 * @param   string  $path
 * @return  mixed
 */
function remove_path($file, $path = UPLOAD_PATH) {
    if(strpos($file, $path) !== FALSE) {
        return substr($file, strlen($path));
    }
}

$file = /var/www/example.com/uploads/myphoto.jpg;

print remove_path($file, /var/www/site.com/);
//prints "uploads/myphoto.jpg"
Run Code Online (Sandbox Code Playgroud)

有谁知道更好的方法来处理这个?

Tyl*_*ter 8

假设目录是/path/to/root/document_root/user/file,地址是site.com/user/file

我展示的第一个函数将获取当前文件相对于万维网地址的名称.

$path = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
Run Code Online (Sandbox Code Playgroud)

并将导致:

site.com/user/file
Run Code Online (Sandbox Code Playgroud)

第二个函数剥离文档根目录的给定路径.

$path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $path)
Run Code Online (Sandbox Code Playgroud)

鉴于我通过/path/to/root/document_root/user/file,我会得到

/user/file
Run Code Online (Sandbox Code Playgroud)

  • 考虑到未使用`$ _SERVER ['PHP_SELF']`可能是有害的. (2认同)

Geo*_*rge 8

更准确的方式(包括主机端口)将使用它

function path2url($file, $Protocol='http://') {
    return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
Run Code Online (Sandbox Code Playgroud)

  • return $ Protocol.$ _ SERVER ['HTTP_HOST'].str_replace($ _ SERVER ['DOCUMENT_ROOT'],'',realpath($ file)); 添加realpath会正确清理输出URL - 当输入在路径中有../或./时. (3认同)

Phi*_*ber 6

恕我直言,这种自动化确实容易出错.使用一些显式路径助手(例如,一个用于上传,一个用于用户图片等)或者仅封装例如带有类的上传文件,你会好得多.

// Some "pseudo code"
$file = UploadedFile::copy($_FILES['foo']);
$file->getPath(); // /var/www/example.org/uploads/foo.ext
$file->getUri();  // http://example.org/uploads/foo.ext
Run Code Online (Sandbox Code Playgroud)