Search code examples
javascriptphpkohana

I can't force download a pdf file


i've tried searching solutions to my problem for about 2 days now and i can't seem to make my code work. My goal is to download a PDF file on a button click but i want the path of the file to be hidden for the users. The project im working on is using Kohana(3.3) framework. I've tried to call that function with ajax :

public function action_download_pdf()
{
        $this->auto_render = false;
        if ($this->request->post()) {

            $data = $this->request->post();
            $file = 'uploads/pdfs_folder/'.$data['pdf_number'].'.pdf';

            if (file_exists($file)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename='.$data['pdf_number'].'.pdf');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file));
                ob_clean();
                flush();
                readfile($file);
                exit;
            }
        }
    }

I'm getting Status Code: 200 OK, but i only get it to show in the "preview" tab on my developer console.

https://i.sstatic.net/vyAiK.jpg

I can't figure out what should i do to dowload it instead of showing it that way ?


Solution

  • So this is how i solved my issue:

    I made a table in my DB in which i generate and save one fake number and one real number. When i reach the step with the button to download the PDF i submit a form thru that button which triggers a function in my Controller. The function is the code i initially posted. I check the fake number in my table and get the real one.