I want to save file programmatically in public path, and I want to know how can I get Public Directory path in Drupal 8. In Drupal 7, I would use the following code.

drupal_realpath(file_default_scheme() . '://')

What is the equivalent in Drupal 8?

  • 2
    Both functions actually still exist, drupal_realpath() is just deprecated. If a function is deprecated, you can almost always just look at its implementation as it then usually calls the new service/API. You can also always search the change records: drupal.org/list-changes/…
    – Berdir
    Jan 3, 2016 at 9:10
  • 1
    Also, two related comments: 1. You're saving in the default path. That might be public but it might also be something else. You can just hardcode public:// if you always want it to be in public. 2. Most API's can handle public:// directly, e.g. any or almost any file* PHP functions like file_put_contents(). There is no reason to convert it yourself. In fact, some stream wrappers like e.g. an amazon S3 storage implementation will not even allow that.
    – Berdir
    Jan 3, 2016 at 9:11

2 Answers 2


According to the realpath API, you can get it with:

\Drupal::service('file_system')->realpath(file_default_scheme() . '://');
  • You're missing the file_default_scheme() part, this doesn't do anything. But that still exists.
    – Berdir
    Jan 3, 2016 at 9:08
  • Added that in an edit.
    – Berdir
    Jan 3, 2016 at 9:08
  • when I do this I get the files-private directory. How do I get the public directory
    – Diana
    Apr 3, 2017 at 15:46
  • 1
    @Diana the code above should give you the public path. To get the private you can do this: \Drupal::service('file_system')->realpath("private://");
    – NickO
    Apr 7, 2017 at 21:33
  • @NickO your code doesn't works for me for the private filesystem path May 12, 2017 at 18:44

In case you want to get just "sites/default/files" or "sites/your-multisite/files" Then you should use

// Add to the top of the file.
use Drupal\Core\StreamWrapper\PublicStream;

// In your method.
print PublicStream::basePath();
  • and Drupal\Core\StreamWrapper\PrivateStream::basePath() for private file path
    – Permana
    May 25, 2021 at 2:24

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.