stack stack - 7 months ago 27
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";
$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');
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
(button), it opens that
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


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:

$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));

Source: PHP Readfile Documentation