Jonnny
Jonnny

Reputation: 5039

Display images from protected folder

I have a protected folder within Yii and I'm looking to display some of those images within the site. I've tried the following code and it works within the site/index controller in that it returns just the image I wanted.

However when I tried to separate the code it didn't work. Any help is appreciated.

Model

    public function getImage() // will take file identifier as @param       
{

    $imageID = '2562584569'; // will eventually be dynamically assigned

    $image = Images::model()->find('tmp_name=:id', array('id' => $imageID)); 

    $dest = Yii::getPathOfAlias('application.uploads');

    $file = $dest .'/' . $image->tmp_name . '.' . $image->extension;

    if(file_exists($file)){
    ob_clean();
    header('Content-Type:' . $image->logo_type);
    readfile($file);
    exit;
    }

}

And in the view

CHtml::link('<img src="' . Yii::app()->request->baseUrl .'/images/image" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));

Thanks

Jonnny

Upvotes: 1

Views: 5366

Answers (2)

Jonnny
Jonnny

Reputation: 5039

I went about it like this

CHtml::link('<img src="' . $this->createUrl('/images/image', array('data'=>$data['data'])) . '" />', array('product/index', 'id'=>$data['product_id'], 'slug'=> $data['product_slug']));

Model

public function actionImage($data)       
{

$image = Images::model()->find('tmp_name=:data', array('id' => $data)); 

$dest = Yii::getPathOfAlias('application.uploads');

$file = $dest .'/' . $image->tmp_name . '.' . $image->extension;

if(file_exists($file)){
ob_clean();
header('Content-Type:' . $image->logo_type);
readfile($file);
exit;
}

}

Thanks for all help

Upvotes: 1

Sankalp Singha
Sankalp Singha

Reputation: 4546

"protected" folder are not accessible from the client browser. This prevents people to have access to important files, like your source code.

If you want to store images inside "protected" and want them to be accessible, you need to publish them using CAssetManager.

Usage is something like:

$path = Yii::app()->basePath.'/path-inside-protected';
$yourImageUrl = Yii::app()->assetManager->publish($path);

Yii will then use the file as an asset, coping it to the "assets" folder, sibling to "protected". After that, you can just use the url returned on your HTML.

<img src="<?php echo $yourImageUrl ?>">

Upvotes: 2

Related Questions