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

11,596

Solution 1

I resolved by added meta data in the head of the page:

<head>
      <meta http-equiv="X-FRAME-OPTIONS" content="DENY">
</head>

Solution 2

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.

Solution 3

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');
Share:
11,596
BasicCoder
Author by

BasicCoder

Updated on June 04, 2022

Comments

  • BasicCoder
    BasicCoder almost 2 years

    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