13

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 Mar 8 '16 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 Mar 8 '16 at 9:54
  • 1
    Post it as a response and accept it as solution. That will help others with the same question. – Aram Boyajyan Mar 8 '16 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) – usernameabc Aug 13 '18 at 20:20
18

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');
| improve this answer | |
  • 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 – usernameabc Aug 13 '18 at 20:12
14

@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.

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();
| improve this answer | |

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.