Php codes for downloading Excel file is not working

2.9k Views Asked by At

I can't download excel file, it downloads the file but it doesn't have a contents and its size is 0kb. This is my html code.

<h5 style="color: red;">
    <a href="2.php?file=files/Battle_Entry_form.xls" class="links">
        Click here to download A Registration form
    </a>
</h5> <br />

2.php (this is my php codes for downloading excel file)

<?php 
if(isset($_GET['file'])){
    $filename = $_GET['file'];

    header('Content-type: application/vnd.ms-excel');

    header('Content-Disposition: attachment; filename="'.$filename.'"');

    readfile("http://www.caledtech.com/batllewebsite/".$filename);
    exit;
}
?>

Is there something missing in my codes?

2

There are 2 best solutions below

2
On

The PHP manual of readfile said:

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

I think you should use file_get_contents instead of readfile:

echo file_get_contents("http://www.caledtech.com/batllewebsite/".$filename);

And I recommend to you to use basename for the filename:

header('Content-Disposition: attachment; filename="'.basename($filename).'"');
0
On

Consider using PHPExcel

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
$objWriter->save('php://output');

How to use PHPExcel

If the content of the Excel file contains gibberish, try adding ob_clean(); or ob_end_clean(); right before saving at this line: $objWriter->save();