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
URL http://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?
Solution 1. There is no way to convert it, unless you are going to buy a hosting and domain using your desired domain name.
get_theme_file_path( string $file = '' ): string Retrieves the path of a file in the theme.
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); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With