Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set/change content-type headers for an entire Zend Framework Application

I've already seen this question: Zend Framework how to set headers and I am aware of how to set headers on a per controller basis.

$this->getResponse() ->setHeader('Content-type', 'text/html; charset=utf-8')

However i'd like to set the content-header in my config file and have it set all my responses to use that content type. Is there some built in method/convention I'm missing out on? I'll settle for setting something in the bootstrap as 2nd best choice.

This is in my config:

resources.view.doctype = "XHTML1_STRICT"
resources.view.encoding = "UTF-8"
resources.view.contentType = "text/html;charset=utf-8"

and I'm using modules and layouts if its any help (default module in this case)

Regards.

like image 232
James Butler Avatar asked Dec 22 '22 14:12

James Butler


2 Answers

You can write a plugin for this which automatically sets the content-type to a default when no other content-types have been set already. Example:

class YourApp_Controller_Plugin_ContentType extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopShutdown()
    {
        $response = $this->getResponse();
        $http_headers = $response->getHeaders();

        /**
         * Check whether the Content-Type header is defined.
         */
        $content_type_found = false;
        foreach ($http_headers as $_header)
        {
            if ($_header['name'] === 'Content-Type')
            {
                $content_type_found = true;
                break;
            }
        }

        /**
         * When no Content-Type has been set, set the default text/html; charset=utf-8
         */
        if (!$content_type_found)
        {
            $response->setHeader('Content-Type', 'text/html; charset=utf-8');
        }
    }
}
like image 152
Jasper van Wanrooy Avatar answered May 17 '23 04:05

Jasper van Wanrooy


There is no need for checking if the header was already set. Since setHeader() will by default leave existing header with the same name without replacing.

class YourApp_Controller_Plugin_ContentType extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopShutdown()
    {
        $response = $this->getResponse();

        /**
         * When no Content-Type has been set, set the default text/html; charset=utf-8
         */
        $response->setHeader('Content-Type', 'text/html; charset=utf-8');
    }
}
like image 37
Danila Vershinin Avatar answered May 17 '23 03:05

Danila Vershinin