I have a string
$directory = "/home/ .../sites/default/files..."
I tried to get the absolute url with:
$MYURL = Url::fromUri("base://".$directory);
That leads to an exception!
Can anybody explain hot to retrieve the url from a string?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI have a string
$directory = "/home/ .../sites/default/files..."
I tried to get the absolute url with:
$MYURL = Url::fromUri("base://".$directory);
That leads to an exception!
Can anybody explain hot to retrieve the url from a string?
Thx for your comments,
but I found the answer by investigating the core modules:
preg_match('/sites(.*)/',$directory,$matches);
$url_new = $matches[1];
$MYURL = Url::fromUri('base:/sites'.$url_new, array('absolute' => TRUE))->toString();
Hope this helps some other guys too!
Based on that string alone you'll never get a url. Do you mean how do you get the url of the current site?
In Drupal you don't need to. As Ivan recommended in his comment, you just need
This is the way to do it if the file was uploaded in Drupal and you have the uri.
file_create_url($path)
https://api.drupal.org/api/drupal/core!includes!file.inc/function/file_create_url/8
If you don't have the URI (for example you need to link to a file in your theme, then use:
drupal_get_path('theme', 'your_theme');
https://api.drupal.org/api/drupal/core%21includes%21bootstrap.inc/function/drupal_get_path/8
Then combine that with a link relative to the theme instead of relative to the server root like your current $directory is:
$directory = "files/myfile.png";
Then jam them together:
$my_url = drupal_get_path('theme', 'your_theme')."/".$directory;
If you do need the full site URL for some reason, you should be able to use global $base_url;
(a global variable in Drupal) or check out https://stackoverflow.com/a/14500505/430191