user3428185
user3428185

Reputation: 1

download file with php

i want to create a link to download an excel file from the root in server computer, using php. so i wrote a simple code as below,

   <?php

   header("Content-disposition: attachment;     filename=example.xls");

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

   readfile("example.xls");

   ?>

it then can be downloaded however when i want to open it, i got the error saying the file i downloaded is in a different format than specified by the file extension. i also tried the same method with jpeg file and didnt get the same error but when i click it, it shows nothing. can someone help me? im not very good with programming. thank you in advance!

Upvotes: 0

Views: 96

Answers (1)

Shidil Eringa
Shidil Eringa

Reputation: 341

Try this

    $file='example.xls';  $filesize=filesize($file);
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
    header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header("Content-Length: " . $filesize);
$fh = fopen("$file, "rb");

// output file
while(!feof($fh)) 
{
# output file without bandwidth limiting
    print(fread($fh, filesize($file))); 
}
fclose($fh);

Upvotes: 1

Related Questions