Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: how to change/add response headers?

Tags:

http

php

web

yii2

I have some truble with Yii2. I try to add/set response headers in my controller's action. Below is code:

   Yii::$app->response->headers->set('Content-type', ['application/pdf']);
   Yii::$app->response->headers->set('Content-Disposition', ['inline', 'filename=' . $fileName]);
   Yii::$app->response->headers->set('Content-Transfer-Encoding', ['binary']);
   Yii::$app->response->headers->set('Content-Length', [$fileSize]);
   Yii::$app->response->headers->set('Accept-Ranges', ['bytes']);

   return readfile($filePath);

If I change set() to add(), or second argument from array to string so get no reaction. Pdf file is not opened. But if I use native PHP header() method - all works correct.

like image 450
illatif Avatar asked Dec 04 '25 11:12

illatif


1 Answers

The Yii2 super easy way to send files as download is

public function actionDownload()
{
    return \Yii::$app->response->sendFile('path/to/file.txt');
}

For more info see the documentation

like image 98
WeSee Avatar answered Dec 07 '25 00:12

WeSee