PHP - 将文件系统路径转换为URL [英] PHP - Convert File system path to URL
问题描述
example.com/uploads/myphoto.jpg
这样的URL访问文件。 由于上传路径通常对应于我构建的功能,似乎大部分时间工作的URL。以这些路径为例:
文件系统
/var/www/example.com/uploads/myphoto.jpg
如果我有一个变量设置为 / var /www/example.com /
然后我可以从文件系统路径中减去它,然后用它作为图像的URL。
/ **
*从文件/路径字符串中移除给定的文件系统路径。
*如果文件/路径不包含给定的路径 - 返回FALSE。
* @param字符串$文件
* @param字符串$路径
* @return混合
* /
函数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/);
//打印uploads / myphoto.jpg
有谁知道更好的方法来处理这个问题?
/ path / to / root / document_root / user /文件
和地址是 site.com/user/file
第一个函数
$ path = $ _SERVER ['SERVER_NAME']显示当前文件的相对于万维网地址的名称。 ]。 $ _SERVER [ PHP_SELF];
会导致:
site.com/user/file
第二个函数剥离给定的
$ p $ $ $ $ $ $ path $ str_replace($ _ SERVER ['DOCUMENT_ROOT'],'',$ path)
由于我在 / path / to / root / document_root / user / file ,我会得到
/ user / file
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
.
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:
File System /var/www/example.com/uploads/myphoto.jpg
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?
Assume the directory is /path/to/root/document_root/user/file
and the address is site.com/user/file
The first function I am showing will get the current file's name relative to the World Wide Web Address.
$path = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];
and would result in:
site.com/user/file
The second function strips the given path of the document root.
$path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $path)
Given I passed in /path/to/root/document_root/user/file
, I would get
/user/file
这篇关于PHP - 将文件系统路径转换为URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!