0

I have a file with an uri and I want to get its raw and relative path.

Uri: public://videos/Test Video.mp4 Path: /sites/default/files/videos/Test Video.mp4

I found already a way to do this:

$file_uri = $file->getFileUri();
// public://videos/Test Video.mp4

$absolute_url = file_create_url($file_uri);
// https://www.example.com/sites/default/files/videos/Test%20Video.mp4

$relative_url = file_url_transform_relative($absolute_url);
// /sites/default/files/videos/Test%20Video.mp4

$relative_raw_url = rawurldecode($relative_url);
// /sites/default/files/videos/Test Video.mp4

Is this the Drupal-way? Or is there a better solution for doing this?

  • the question seems to invite opinions here. Is there a certain concern or worry you have about using the File API functions here? – Shawn Conn Mar 15 at 20:22
  • Hi @ShawnConn! Thanks for your comment. Well I hope it's not just a thing of opions. I want to ask for a better solution if there is a better solution. I have a $file and I want to have the relative path. Do I really have to call 4 different File API functions? – btemperli Mar 16 at 14:10
  • I think I understand the concern. See below. – Shawn Conn Mar 16 at 22:19
2

The "Drupal way" is always a fuzzy term because there's usually more than one answer that works.

Anyway, if you're looking for something less verbose, it would help to look at the File object and it's url() method. That saves you some steps and might save you some work down the road if the old D7 file module API functions get slated for depreciation (like file_load has).

Lastly, it always helps to use native PHP functions when you can since they make things more portable. To wit, parse_url() allows you to slice/dice URLs to the components you want.

Putting it all together, rawurldecode(parse_url($file->url(), PHP_URL_PATH)) pulls all your function call together for one result.

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.