Proxy script to retrieve images from protected directory

Since it took me quite some time to get this done today, I though I share this here for any others interested.

The goal is to retrieve images that have been stored in a protected directory (outside the web root). To this end, you need a action in your Controller:


 * Returns the Image


public function actionGetImage($id, $inline) {

  $model = Image::findOne($id);


  $file = $model->path;

  if (file_exists($file)) {

    Yii::$app->response->sendFile($file, rand(10000000,99999999), ['mimeType' => 'image/jpeg', 'inline' => $inline]);



In your view, post the url to the action as your src:

Html::img(Yii::$app->urlManager->createUrl(['image/get-image', 'id' => $image->id, 'inline' => true]));

And that’s it! I simplified the code snippets and hope I didn’t make any mistakes in that process. Otherwise I think you’re able to figure it out ;) Enjoy!