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

@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();

Tags:

Files

8