我经常发现我的项目文件需要从文件系统以及用户浏览器访问。一个例子是上传照片。我需要访问文件系统上的文件,以便我可以使用GD来更改图像或移动它们。但是,我的用户还需要能够访问像example.com/uploads/myphoto.jpg这样的URL的文件。
因为上传路径通常对应于URL,我构成了一个似乎在大部分时间工作的功能。以这些路径为例:
File System
/var/www/example.com/uploads/myphoto.jpg
URL
07000
如果我有一个变量设置为/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"
有没有人知道一个更好的方法来处理这个?