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

标签 php url filesystems

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

因为上传路径通常与 URL 相对应,所以我编写了一个似乎大部分时间都有效的函数。以这些路径为例:

File System /var/www/example.com/uploads/myphoto.jpg

URL 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"

有谁知道处理这个问题的更好方法吗?

最佳答案

更准确的方法(包括主机端口)是使用这个

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

关于PHP - 将文件系统路径转换为 ​​URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1240462/

相关文章:

php 从字符串中获取子字符串

ruby-on-rails - 自定义设计路径名

swift - 使用 Swift 替换文件系统中的文件夹

linux - 当我使用 VIM 保存文件时会发生什么?

php - 更改登录密码后是否需要重新启动mysql服务器?

php - 在数据库中不存在行时在 PHP OOP 中插入查询

php - mysql 中非常奇怪的错误。与搜索匹配是有效的,但对它来说是无效的

javascript - 带有远程结果和缓存的 jQuery 类别搜索

image - 当我将 URL 从网站粘贴到 Facebook 或 slack 等时,如何显示图像

database - 将图像(jpg、gif、png)存储在文件系统或数据库中?