How do I force a text file to be downloaded? [duplicate]

0

How do I force a text file to be downloaded?

I have this code but it is not downloaded, when I click the link your content is displayed by the browser.

<?php

include "conecte.php";

$querymail = mysql_query("select cod,name from usuarios");
fopen("listar.txt", "w+");
while($data = mysql_fetch_array($querymail)) {
    $log = str_pad($data[0], 30, " ", STR_PAD_RIGHT);
    $log2 = str_pad($data[1], 30, "0", STR_PAD_RIGHT);
    if (!$savelog = fopen('listar.txt', "a")){
        exit;
    }        
    if (!fwrite($savelog, $log . $log2. "\r\n")){
        exit; fclose($savelog); 
    }
}
?>


<a href="listar.txt">Clique aqui para baixar</a>
    
asked by anonymous 11.04.2016 / 16:12

2 answers

2

Create a new file (download.php) in it define the header to be sent or in which format the browser should interpret the information open the file and send it to the client.

download.php

header('Content-disposition: attachment; filename=lista.txt');
header('Content-type: text/plain');
$str = file_get_contents('log/lista.txt');
echo $str;

Call:

<a href="download.php">Clique aqui para baixar</a>

A more optimized option, quoted by Wallace Maxters is to change% with% by% with% / p>

header('Content-disposition: attachment; filename=lista.txt');
header('Content-type: text/plain');
readfile('log/lista.txt');

Related:

PHP readfile vs. file_get_contents

    
11.04.2016 / 16:44
2

The question has been answered, but there is another solution or complement. You can use the download attribute in a a tag:

<a href="LocalDoArquivo" download="NomeDoArquivo"> Texto </a>

Example:

<a href="http://pt.stackoverflow.com/questions/122672/como-for%c3%a7ar-o-download-de-um-arquivo-de-texto" download="Baixou ao invés de acessar"> Baixar </a>

This way you will download the HTML from this page, rather than accessing it normally.

This is new, inserted in HTML 5!

Support:

Chrome: 14.0+
Internet Explorer: 13.0+
Mozilla: 20.0+
Safari: Não suportado
Opera: 15.0+
    
14.04.2016 / 02:15