PHP - 将文件系统路径转换为 URL [英] PHP - Convert File system path to URL
问题描述
我经常发现我的项目中有需要从文件系统和用户浏览器访问的文件.一个例子是上传照片.我需要访问文件系统上的文件,以便我可以使用 GD 更改图像或移动它们.但我的用户还需要能够从像 example.com/uploads/myphoto.jpg
这样的 URL 访问文件.
I often find that I have files in my projects that need to be accessed from the file system as well as the users browser. One example is uploading photos. I need access to the files on the file system so that I can use GD to alter the images or move them around. But my users also need to be able to access the files from a URL like example.com/uploads/myphoto.jpg
.
因为上传路径通常对应的是URL,所以我编了一个似乎大部分时间都可以工作的函数.以这些路径为例:
Because the upload path usually corresponds to the URL I made up a function that seems to work most of the time. Take these paths for example:
文件系统/var/www/example.com/uploads/myphoto.jpg
File System /var/www/example.com/uploads/myphoto.jpg
网址http://example.com/uploads/myphoto.jpg
如果我将变量设置为类似 /var/www/example.com/
的内容,那么我可以从文件系统路径中减去它,然后将其用作图像的 URL.>
If I had a variable set to something like /var/www/example.com/
then I could subtract it from the filesystem path and then use it as the URL to the image.
/**
* 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"
有没有人知道处理这个问题的更好方法?
Does anyone know of a better way to handle this?
推荐答案
更准确的方式(包括主机端口)是使用这个
More accurate way (including host port) would be to use this
function path2url($file, $Protocol='http://') {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
这篇关于PHP - 将文件系统路径转换为 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!