So, I have this problem with my download link. Basically, my previous way of creating a download link is to simply create a form button with the = 'link' method, and the action is a link to the file. This works for firefox and others, but not for safari. For some reason, when a user tries to download a file (excel file) from safari, he simply displays a bunch of ascii characters in the browser (I think he is trying to read it using the browser?). Well, I was looking for another solution, and it seems like using a header is a way to do this. So now I am trying to create a form button with the = = post and action = 'download.php' method, where there is a hidden field with a link to the file. Looks like this
function showDownloadWithHeader($link){ echo "<form action='download.php' method='post' >"; echo "<input class='downloadButton' type='submit' value='Download Report'>"; echo "<input type='hidden' name='filename' value='$link'>"; echo "</form>"; }
And inside download.php I just want the user to ask to download the file.
<?php if($_POST['filename'] == '' || empty($_POST['filename'])){ exit; } $filename = $_POST['filename']; //the file is 2 folder down. eg data/stack/bla.xlsx $file = $filename; $extension = end(explode('.', $filename)); error_reporting(E_ALL); ini_set("display_errors",1); // echo $filename; // echo "<br/>"; // echo $extension; // echo filesize($filename); // echo "<br/>"; switch($extension){ case 'xls': $mimeType = 'application/vnd.ms-excel'; break; case 'xlsx': $mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; break; } // echo $mimeType; header('Content-Description: File Transfer'); header('Content-Type: ' . $mimeType); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($filename); exit; ?>
I saw this solution on php.net under the readfile () function, but it does not seem to work for me. I am doing this on localhost.
source share