Search code examples
cakephpdownloadheadercakephp-4.x

CakePhp 4 add "Content-Type: text/html" when I try to show a PDF


I trying to show a PDF inline but I get binary code instead. The mock that I show below works OK in a simple php file in webroot but show binary code from an entity template.

<?php
header("Content-type: application/pdf"); 
header('Content-Disposition: inline; filename="file.pdf"');    
header("Cache-control: private");
@ readfile('/opt/demo/webroot/document.pdf');
?>

And my layout do not have extra characters before my Headers definition:

<?=$this->fetch('content')?>

I get next information from get_headers():

Array ( [0] => HTTP/1.1 302 Found [1] => Date: Tue, 25 Apr 2023 03:42:42 GMT [2] => Server: Apache [3] => Expires: Thu, 19 Nov 1981 08:52:00 GMT [4] => Cache-Control: no-store, no-cache, must-revalidate [5] => Pragma: no-cache [6] => Set-Cookie: PHPSESSID=givi13cckql8v0oq0lnsvn2rvb; path=/; HttpOnly; SameSite=Lax [7] => Set-Cookie: csrfToken=wbFIJHOSq0HE1K4d0eYljTI2YzUzOWQwMTEyMGEwYjNmMTVhMmM0NTdiYmIxNjU0YTI3MTY3MzE%3D; path=/; HttpOnly [8] => Location: /login?redirect=http%3A%2F%2F107.23.196.88%2Fdocuments%2Fshow%2Ff198a0d3-ffd3-44e3-8715-8f5ed8a05185 [9] => Content-Length: 0 [10] => Connection: close [11] => Content-Type: text/html; charset=UTF-8 [12] => HTTP/1.1 200 OK [13] => Date: Tue, 25 Apr 2023 03:42:43 GMT [14] => Server: Apache [15] => Expires: Thu, 19 Nov 1981 08:52:00 GMT [16] => Cache-Control: no-store, no-cache, must-revalidate [17] => Pragma: no-cache [18] => Set-Cookie: PHPSESSID=avupp24r2uqf66i6d95n6t5hpk; path=/; HttpOnly; SameSite=Lax [19] => Set-Cookie: csrfToken=rfiGOmviqYjfyyyyZbtXVzQ4OTAxNzc5OTc4ZjRmNmI2YmI3ZGZlOWMwYWQ5YWVjMDAyOTg2YmM%3D; path=/; HttpOnly [20] => Vary: Accept-Encoding [21] => Connection: close [22] => Transfer-Encoding: chunked [23] => Content-Type: text/html; charset=UTF-8 ) ?>

Is it necessary to make another change to use Headers in templates?

Thanks in advance


Solution

  • I was able to solve this with Cake\Http\Response::withFile() method in this way.

    public function show ($id){
        $path = '/home/ubuntu/receipts/' . $id . '.pdf';
        $response = $this->response->withFile($file['path']);
        return $response;
    }
    

    Thanks for your help @ndm