How can i get the absolute path for a file based on the fid? Sorry if this is a repeat, I did a search but was unable to find the answer.

  • I might have figured out a way to get it using the $base_url + the remaining path to files + uri is this the best way?
    – Russ
    Feb 28 '14 at 2:56

Drupal 7

This is a two part process, using file_load() and file_create_url()

First, you need to turn the $fid into a Drupal URI:

$file = file_load($fid);
$uri = $file->uri;

Now, you can turn this into a URL

$url = file_create_url($uri);

file_create_url() always creates an absolute URL, either using the global $base_path that you have defined, or using the one that Drupal guessed during bootstrap.

  • 1
    I am surprised you have to load the file just to get the path, seems like a waste of resources.
    – Russ
    Feb 28 '14 at 3:55
  • 2
    @Russ It's loading the file object, not the file itself. You could also do a db_query to get the uri, but I try to use the API as much as possible.
    – mpdonadio
    Feb 28 '14 at 4:05
  • Thanks, I figured that, just thought there would be a clean function that could return it in one step. Maybe something to consider in drupal 8.
    – Russ
    Feb 28 '14 at 13:21
  • 2
    In your example you have 'field_load($fid)', it should be 'file_load($fid)'. Sep 8 '18 at 20:47
  • 2
    @SteveMulvihill Wow, nice catch. Four+ years and 33 votes, and nobody noticed that.
    – mpdonadio
    Sep 8 '18 at 21:42

Drupal 8

$file = \Drupal\file\Entity\File::load($file_id);
$uri = $file->getFileUri();
$url = \Drupal\Core\Url::fromUri(file_create_url($uri))->toString();
  • It works also only by calling file_create_url($uri); which is already returning the URL as a string. Sep 15 '21 at 8:14

In Drupal 7 you can also use MYSQL query, if you don't want to load all the fields of the file

  $fid = 1; //your file ID
  $uri = db_select('file_managed', 'f')
    ->condition('f.fid', $fid, '=')
    ->fields('f', array('uri'))
  echo file_create_url($uri);

These are both working for me in Drupal 8:

// top of file
use Drupal\file\Entity\File;
use Drupal\Core\Url;

// load the file object from some file id
$file_object = File::load(123);

// way 1
$file_uri = $file_object->uri->value;
$file_url = file_create_url($file_uri);

// way 2
$file_uri = $file_object->getFileUri();
$file_url = Url::fromUri(file_create_url($file_uri))->toString();

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.