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?
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');
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
Deprecated
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.
Example:
$file = File::load($file_id);
$uri = $file->getFileUri();
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager')->getViaUri($uri);
$file_path = $stream_wrapper_manager->realpath();
managed files (These are files that have either been uploaded by users or were generated automatically (for example through CSS aggregation))
andshipped files (those outside of the files directory, which ship as part of Drupal core or contributed modules or themes)