8

I'm trying to print out the URL of an image field using the following code.

<img src="<?php echo $field_company_logo['und'][0]['uri']; ?>" alt="<?php echo $company[0]['#markup']; ?>" />

The code gives me a URI like public://company-logos/image.png when I would need sites/default/files/company-logos/image.png.

What code should I use to print the image path (i.e. sites/default/files/company-logos/image.png)?

20

You want to use the drupal_realpath() function to convert the URI into the actual filesystem path.

echo drupal_realpath($field_company_logo['und'][0]['uri']);

You could also use file_create_url() to get the actual URL to the image, as opposed to a local filepath.

And the correct way to render an image is to run it through theme_image():

echo theme('image', array(
  'path' => file_create_url($field_company_logo['und'][0]['uri']),
  'alt' => check_plain($company[0]['#markup']),
));

Also, accessing field data the way you're doing it isn't the preferred method. Have a look at field_get_items() and the detailed example in the Rendering Drupal Fields (the right way) blog entry.

  • 2
    +1 for using the theme function, although I don't think you would actually want drupal_realpath() anymore. The theme function will automatically transform the URI. – Les Lim Nov 14 '13 at 23:06
  • file_create_url worked for me, thanks! realpath gave me the absolute url though which wouldn't render. – Joe Taylor Nov 14 '13 at 23:40
  • You can pass the stream path directly (public://...) and it will automatically generate the right path. – Eduardo Chongkan Jun 8 '16 at 6:42
10

If you literally just want to transform a URI into an actual URL, then you want the file_create_url() function, which is used like this:

$url = file_create_url($uri);

But you might find it easier to use a theme function, like Yuriy Babenko suggests:

$image_vars = array(
  'path' => $field_company_logo['und'][0]['uri'],
  'alt' => $company[0]['#markup'],
);
echo theme('image', $image_vars);

You can easily adapt this to use theme_image_style() instead, if you want a sized derivative of your image.

2

You can use the Image URL Formatter module. It allows to change the field format in order to get only the URL:

Drupal field settings

Bonus: it works with Views as well:

enter image description here

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.