Readfile loads empty file and wrong file type
I am using the below code to load csv file on button click.
Js
$(document).on("click", "#CSV", function () {
var csv_value = $('#result').table2CSV({
delivery: 'value'
});
console.log(csv_value);
$.ajax({
type: "POST",
url: "csv.php",
data: {
csv: csv_value
},
success: function (html) {
window.location.href = "download.php";
}
});
});
csv.php
require_once ("session_start.php");
if (isset ( $_POST ['csv'] )) {
$file = $_POST['csv'];
$_SESSION ['csvf'] = $file;
} else {
echo "No CSV Data";
}
download.php:
session_start();
$file =$_SESSION['csvf'];
$filename = $file."_".date("Y-m-d_H-i",time());
header ( "Content-type: application/vnd.ms-excel" );
header ( "Content-disposition: filename=" . $filename . ".csv" );
readfile($filename);
exit ();
When I execute the function, the uploaded file download.php
, even though the correct headers have been submitted (confirmed with the console), the file is also empty. Also when I use print()
it prints data CSV
, so I know the file is not empty, but it also creates a file .php
and prints all content inside including headers. How do I fix this problem?
Edit
I've tried to crudely force the download using the following code in .htaccess
, to no avail.
<FilesMatch "\.(?i:csv)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
As a result, there is still a file left download.php
.
source to share
The following code worked for me using print()
insteadreadfile()
session_start ();
$file = $_SESSION ['csvf'];
$_table = $_SESSION['table']; //table Name
$filename =$_table."_".date ( "Y-m-d_H-i", time () ).".csv";
header ( "Content-type: text/csv" );
header ( "Content-Disposition: attachment; filename=".$filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
print ($file) ;
exit ();
source to share
You can just copy the location of the script with the filename you want:
success: function (html) {
window.location.href = "download.php/something.csv";
}
It will still launch download.php
, but the browser will only see the final portion of the URL and treat the download as you would expect.
With this, you can also get rid of your hack .htaccess
and minify your PHP code to:
session_start();
$file =$_SESSION['csvf'];
session_write_close();
readfile($file);
source to share