gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:43:41 25 4
gpt4 key购买 nike

我经常发现项目中的文件需要从文件系统以及用户浏览器访问。一个例子是上传照片。我需要访问文件系统上的文件,以便可以使用 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/33581254/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com