illatif illatif - 1 year ago 353
HTTP Question

Yii2: how to change/add response headers?

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.

Answer Source

Method set signature expects string as value so it would be better to replace your arrays with string although it not makes any difference in non-strict coding.

Anyway - based on the getDispositionHeaderValue Content-Disposition should be

'inline; filename=' . $fileName

It would be better to use Yii 2 methods to send the file to browser like:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download