I am creating an Excel reading module in Drupal 8. I want to get the real path of a file for reading it from a path like public://2016-03/Places.xls.

What function should I call for getting the real path of a file?

  • 1
  • 4
    For reading with what? That path works with almost everything, e.g. file_get_contents('public://...') works just fine.
    – Berdir
    Commented Mar 8, 2016 at 7:07
  • 1
    I got the answer in terms of drupal 8 it is ` \Drupal::service('file_system')->realpath('public://2016-03/Places_2.xlsx')`
    – Nisam
    Commented Mar 8, 2016 at 9:54
  • 1
    Post it as a response and accept it as solution. That will help others with the same question. Commented Mar 8, 2016 at 14:29
  • 1
    I had a similar situation, but ended up going with file_create_url because it can handle managed files (These are files that have either been uploaded by users or were generated automatically (for example through CSS aggregation)) and shipped files (those outside of the files directory, which ship as part of Drupal core or contributed modules or themes) Commented Aug 13, 2018 at 20:20

2 Answers 2


Finally I got the solution by digging Drupal code.
We can get the real path or absolute path by using the file_system service.

$absolute_path = \Drupal::service('file_system')->realpath('public://2016-03/Places_2.xlsx');
  • 4
    are these for files upload through Drupal? What happens if they are hosted externally? The use of this method is discouraged, because it does not work for remote URIs. Except in rare cases, URIs should not be manually resolved. is mentioned the documention for FileSystem::realpath Commented Aug 13, 2018 at 20:12

@Nisam answer was right but now it's deprecated: function drupal_realpath


in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0. Use \Drupal\Core\File\FileSystem::realpath().

So you should use FileSystem::realpath. In Drupal 9 is the way to go because drupal_realpath has been removed.


$file = File::load($file_id);
$uri = $file->getFileUri();
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager')->getViaUri($uri);
$file_path = $stream_wrapper_manager->realpath();
  • That was my first thought too.. I'm still missing something because when it gets to Twig, the path gets twisted into /files/... $module_handler = \Drupal::moduleHandler(); $module_path = $module_handler->getModule('company_partners_sync')->getPath(); $premier_tech_image = $module_path . '/images/premier-technology.png'; $variables['default_partner_logo'] = $premier_tech_image;
    – sea26.2
    Commented May 29, 2021 at 4:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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