Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send header with X-Frame-Options DENY with the PHP Yii framework?

I'm trying to DENY iframe calling my website with the PHP framework Yii.

I added this line in the top of 'index.php' or in the 'protected/views/layouts/main.php'

<?php header("X-Frame-Options: DENY") ?>

But I still have the possibility to create an iframe with the 'src' property of my website!

I'm trying too : add in the '.htaccess' :

Header always append X-Frame-Options DENY
like image 344
BasicCoder Avatar asked Dec 08 '25 09:12

BasicCoder


2 Answers

You can do this by configuring the response component of the application and adding custom headers in the beforeSend event, e.g.:

return [
    ...
    'components' => [
        ...
        'response' => [
            'on beforeSend' => function($event) {
                $event->sender->headers->add('X-Frame-Options', 'DENY');
            },
        ],
        ...
    ],
];

This will add the header(s) for all responses. This may not be appropriate, in which case, you can use \Yii::$app->response->headers->add($name, $value); before returning from an action or in the afterAction() method of the controller.

It is well documented that the meta http-equiv tag does not work for this situation. In my opinion, http-equiv should never be used if you can set the header properly server-side.

The reason that the PHP header() function does not work is because Yii's response component resets all headers before preparing the response to send.

like image 103
spikyjt Avatar answered Dec 10 '25 00:12

spikyjt


Here is the documentation on how to modify headers sent by YII framework (v2)

http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#http-headers

HTTP Headers

You can send HTTP headers by manipulating the header collection in the response component. For example,

$headers = Yii::$app->response->headers;

// add a Pragma header. Existing Pragma headers will NOT be overwritten.

    $headers->add('Pragma', 'no-cache');

// set a Pragma header. Any existing Pragma headers will be discarded.

    $headers->set('Pragma', 'no-cache');

// remove Pragma header(s) and return the removed Pragma header values in an array

    $values = $headers->remove('Pragma');
like image 43
Craig London Avatar answered Dec 10 '25 00:12

Craig London