Peter's blog about cruft and more

05 February

Retrieve real path of file in Drupal 7

Drupal 7 uses the DrupalPublicStreamWrapper-class to handle all the files that are upload to a node or served to the audience. When you take a look at the node object you will see that the path where the file is stored is not directly clear. For example:

[0] => Array (
[fid] => 14
[display] => 1
[description] =>
[uid] => 1
[filename] => index.html
[uri] => public://htmlclean/index_3.html
[filemime] => text/html
[filesize] => 38941
[status] => 1
[timestamp] => 1296904269

In this example you can see that the file index.html is saved as index_3.html and available at the URI public://htmlclean/index_3.html. For one off my modules I needed the real path. I will explain how I retrieved it. In the example below the $file_array is the array as shown in the example above.

$scheme = file_uri_scheme($file_array['uri']);
$wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
$path = $wrapper->getDirectoryPath() . '/' . file_uri_target($file_array['uri']);

The result of $path is the following: sites/default/files/htmlclean/index_3.html. If you want a web-accessible URL . Simply use file_create_url($uri).

If there is a faster way to do this let me know! Or else you can use this snippet to retrieve the real path of file in Drupal 7.

No comments

Place your comment

Please fill your data and comment below.
Your comment