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?
Try this:
This simple snippet can convert the file path to file's url on the server. Some settings like protocol and port should be kept.
The code below is well commented:
I've used this and worked with me:
And if you need the directory name in url format add this line:
More accurate way (including host port) would be to use this