stack stack - 1 month ago 8
PHP Question

Why JS opens a txt file instead of downloading it?

Here is my code:

Server Side:

public function export(){
$arr = array();
if($_POST["type"] == "save"){
$name = "export.txt";
file_put_contents("$name",$_POST["text"]);
$arr["type"] = "link";
$arr["url"] = "http://localhost:8000/{$name}";
}
return $arr;
}


Client Side:

$(document).on('click', '#export', function () {
var names = ["سعید خرمی", "فرید هادوی"];
var namess = names.join('\n');
$.ajax({
type: "post",
url: "/export",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
type: "save",
text: namess
},
dataType: "json",
success: function(data){
var href = data.url;
window.location = href;
}
});
})


When I click on
#export
(button), it opens that
.txt
file (instead of downloading it). Something like this:

enter image description here

Noted that I use chrome .. Also it doesn't work in other browsers.

How can I force it to download that
.txt
file?

Answer

Change your success part like this,

success: function(data){
var href = download.php?filename=export.txt;
window.location = href;
}

And in your download.php:

Get the file name from the GET variable filename (say as $file).

Send the headers:

<?php
$file = $_GET['filename']; // get the filename
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: text/plain'); // the appropriate header type for txt file
    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;
}
?>

Source: PHP Readfile Documentation