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?

  • 2
    file_create_url($path) – user21641 Jan 10 '16 at 23:35

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');


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


Thx for your comments,

but I found the answer by investigating the core modules:

$url_new = $matches[1];
$MYURL = Url::fromUri('base:/sites'.$url_new, array('absolute' => TRUE))->toString();

Hope this helps some other guys too!

  • 2
    a) \Drupal::service('site.path') and b) if we're talking files here then Url::fromUri('public://somefile/somewhere/is.jpg')->toString(). – user21641 Jan 11 '16 at 14:09
  • 1
    This should work for any uri string (public:, base:, internal:, or absolute). $urlObj = \Drupal\Core\Url::fromUri($uriString); $urlObj->toString(); – ben.hamelin Dec 6 '18 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.