Search code examples
php.htaccesscodeigniterforce-download

Not force_download with images and pdf files in codeigniter


Hello friends I have one problem about force_download function, I have an upload form on the website and I am using this function to download the data that I upload and it´s works

public function download($file)
    {
        force_download('./uploads/'.$file, NULL);
    }

but you know that pdf,png,jpg files can be directly seen in the navegator if you want you needn´t to download it but if I use this function all files are downloaded, how I could to get it?

I try to use the direct link to my upload folder but it can be possible because I have a .htaccess file that denied the access to prevent that log in users only can download something.


Solution

  • As I already wrote, make check in if elseif else or even maybe better switch case block with checking file extension before download/preview code. Something like:

    public function download($file)
    {
        //get the file extension
        $info = new SplFileInfo($file);
        //var_dump($info->getExtension());
    
        switch ($info->getExtension()) {
            case 'pdf':
            case 'png':
            case 'jpg':
                $contentDisposition = 'inline';
                break;
            default:
                $contentDisposition = 'attachment';
        }
    
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/pdf');
            // change inline to attachment if you want to download it instead
            header('Content-Disposition: '.$contentDisposition.'; filename="'.basename($file).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
        }
        else echo "Not a file";
    }