Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the full URL to an image in Cakephp?

Let's say I have an "image.jpg" stored in the assets folder and the path is "www.example.com/public" and I want only the string path to the image. How do I get this? I do NOT want the html tags only the path string.

like image 856
Johnathan Au Avatar asked Apr 13 '13 15:04

Johnathan Au


2 Answers

Look inside the source code of HtmlHelper::image() to see how this helper creates the right URL; Slightly modified, this is how it's achieved:

$imageUrl = $this->assetUrl('image.jpg', array(
    // note: only required if you need the
    // URL -including- http://example.com
    'fullBase'   => true,
    'pathPrefix' => IMAGES_URL
));

The source code for Helper::assetUrl() can be found here: https://github.com/cakephp/cakephp/blob/2.3.2/lib/Cake/View/Helper.php#L305

like image 128
thaJeztah Avatar answered Oct 11 '22 17:10

thaJeztah


After trying the various CakePHP global constants (ROOT, WEBROOT_DIR, WWW_ROOT, CSS, etc.) with no results, the general solution seems to be found in the $this->webroot property that returns the path to the application webroot. Thus for the various cases above we may have in our layouts, views or elements:

A simple image tag:

<img src="<?php echo $this->webroot; ?>img/foo.gif" .../ > 

A background image within a table cell the old way:

<td background="<?php echo $this->webroot; ?>img/foo.gif"> 

An input of type="image":

<input type="image" src="<?php echo $this->webroot; ?>img/go_btn.gif" ... /> 
I think webroot always work
like image 28
Ravindra Shekhawat Avatar answered Oct 11 '22 17:10

Ravindra Shekhawat