I'm using php from with a view (Views PHP) I'm trying to extract the real url of a file from a file reference. I am able to get the the uri of the file and or the filename. What drupal function can I use to get thee actual public URL of the file?.

$videouri = db_query('SELECT filename FROM `file_managed` WHERE fid = ' . $nidvideo)->fetchColumn();
//drupal_set_message('<pre>'. print_r($videourl, TRUE) .'</pre>');
$realpath = drupal_realpath($videouri);
$videourl = file_create_url($realpath);

What do you mean by "public URL" exactly ?

file_create_url() can give the absolute URL to the image out of the box.

$videouri = db_query('SELECT uri FROM {file_managed} WHERE fid = :nidvideo', array(':nidvideo' => $nidvideo))->fetchColumn();
//drupal_set_message('<pre>'. print_r($videourl, TRUE) .'</pre>');
$videourl = file_create_url($videouri);

file_create_url() expects a valid uri. drupal_realpath() gives the server path which does not work.

I also changed your database query to avoid any SQL injection vulnerable.

| improve this answer | |

Don't use drupal_realpath() as it has been deprecated now.

Either of the following can be used:

1. (file_stream_wrapper_get_instance_by_uri($uri)):

$uri = $field[0]['uri'];  // file path as uri: 'public://';
if ($wrapper = file_stream_wrapper_get_instance_by_uri($uri)) {
  $path = $wrapper->realpath();

2. (file_create_url($uri)):

$uri = $node->field_video['und'][0]['uri'];  // file path as uri: 'public://';
$video_path = file_create_url($uri);
| improve this answer | |
  • @user379468 Has the above solution worked for you, or if you found some better solution than please share. Thanks!! – Ankit Agrawal Oct 1 '13 at 20:47
  • This is a common misconception that is incorrect. drupal_realpath() is not deprecated -- it's just discouraged in cases where a path could be remote, since it only works for local paths. The first code snippet posted above is exactly what drupal_realpath() does under the hood. – GuyPaddock Jan 9 '19 at 16:20
  • To clarify: my comment is specific to Drupal 7. Either way, I still stand by my assertion that using the same code as what's inside a deprecated function is no better than just calling the deprecated function. – GuyPaddock Jan 9 '19 at 16:29

Check the following example:

$url = file_stream_wrapper_get_instance_by_uri($filepath)->getExternalUrl()

See: API for DrupalPublicStreamWrapper.


| improve this answer | |

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.