Search code examples
imagecakephpcontent-type

Change the content type to image/png - cakephp


I have a cakephp application .I understand that my app uses a default.ctp for its layout .In default layout my header is set to html/text .I want to change my header type to image/png .Where should i change it ? Pls someone help me

Code:

$this->layout=NULL; 
$this->autoRender=false; 
$this->RequestHandler->respondAs('image/jpg');

      View Coding :(index.ctp)
           <?php 
           session_start(); 
           $text = rand(10000,99999); 
           $_SESSION["vercode"] = $text; 
           $height = 25; 
           $width = 65; 

           $image_p = imagecreate($width, $height); 
           $black = imagecolorallocate($image_p, 0, 0, 0); 
            $white = imagecolorallocate($image_p, 255, 255, 255); 
            $font_size = 14; 
            imagestring($image_p, $font_size, 5, 5, $text, $white); 
            imagejpeg($image_p, null, 80); 
                  ?>
           Controller coding :

                public function index() 
                {
                      $this->layout=false;
                      $this->response->type('png');
                } 

Note: CakePHP version 2.3.0


Solution

  • If you really must return the content of your view/layout as image (which I highly doubt):

    $this->response->type('png'); // as documented in the 2.x docs
    

    will automatically set image/png as response type for the header.

    If you need to render your view without layout try

    $this->layout = false;
    // OR
    $this->render('my_view', false); // false should not render a layout
    

    You cannot use "null" as it renders the default layout.

    Either way, never call header() stuff in your view, always in your controller via response object.