15

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
  • 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
    Commented 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
    Commented Jan 3, 2016 at 9:11

2 Answers 2

25

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

\Drupal::service('file_system')->realpath(file_default_scheme() . '://');
5
  • You're missing the file_default_scheme() part, this doesn't do anything. But that still exists.
    – Berdir
    Commented Jan 3, 2016 at 9:08
  • Added that in an edit.
    – Berdir
    Commented Jan 3, 2016 at 9:08
  • when I do this I get the files-private directory. How do I get the public directory
    – Diana
    Commented 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
    Commented Apr 7, 2017 at 21:33
  • @NickO your code doesn't works for me for the private filesystem path Commented May 12, 2017 at 18:44
6

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();
1
  • and Drupal\Core\StreamWrapper\PrivateStream::basePath() for private file path
    – Permana
    Commented 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.