PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, March 9, 2022

[FIXED] CakePHP 3, how to render without CTP

 March 09, 2022     cakephp, cakephp-3.0, php     No comments   

Issue

How do I render without my controller attempting to load a non-existent .ctp file.

This is my code:

        //without this, I get an error trying to load a non-existent .ctp file. When I include it, the browser does not render the PNG file.
        $this->autoRender = false;

        //... get avatar code

        if (!file_exists($avatarPath))
            throw new Exception('Could not find file: '.$avatarPath);

        $file = file_get_contents($avatarPath);

        header('Content-Type: image/png');
        if ($file === false)
            throw new Exception('file_get_contents failed on avatarPath');
        else
            echo $file;

When I use $this->autoRender = false;, the header call appears to be ignored. Any ideas?


Solution

Read about how to send files with CakePHP. Let me quote the documentation for you:

There are times when you want to send files as responses for your requests. You can accomplish that by using

public function sendFile($id)
{
    $file = $this->Attachments->getFile($id);
    $this->response->file($file['path']);
    // Return response object to prevent controller from trying to render
    // a view.
    return $this->response;
}

As shown in the above example, you must pass the file path to the method. CakePHP will send a proper content type header if it’s a known file type listed in Cake\Network\Reponse::$_mimeTypes. You can add new types prior to calling Cake\Network\Response::file() by using the Cake\Network\Response::type() method.

If you want, you can also force a file to be downloaded instead of displayed in the browser by specifying the options:

$this->response->file(
    $file['path'],
    ['download' => true, 'name' => 'foo']
);


Answered By - floriank
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing