How to force download a file in Joomla 3?

334 Views Asked by At

Wrote a custom module for Joomla. The user enters a file name in the text filed and the pdf file with the entered value as name should be downloaded. But when clicked the page is redirected to home page. Here's the code

$file = $_POST['posttext'] . '.' . 'pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; 
    filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

Tried adding ob_flush() as one of the asker suggested but no good. The code works perfectly as a separate php file.

1

There are 1 best solutions below

0
Jake Dickerson On

Try the following

    $app = JFactory::getApplication();
    $file = $app->input->get('posttext') . '.pdf';
    if (JFile::exists($file)) {
            // File headers
            header("Content-type: application/pdf");
            header("Content-Disposition: attachment");

            // File contents.
            readfile($file);
    }

If you are still having issues, you could check if the file exists in Joomla and download the file in a new tab/window using window.open()