Create text file and download without storing it on the server

Asked

Viewed 1,137 times

1

How can I create a file at script run time to download it, but without having to save to the server directory?

Something like:

$dataOutput = "5s6a56sa565sa65a6s56sa565sa656sa565sa656as56sa556as5as";

//download
header('Content-Description: File Transfer'); ...
echo $dataOutput;
  • 1

    Just a curiosity, what’s the point?

  • When I need to generate a csv file or spreadsheet with database data

1 answer

2

PHP

if($_SERVER['REQUEST_METHOD']=='POST'){

    $content = $_POST['meuTextarea'].PHP_EOL;

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    // Indica o nome do arquivo como será "baixado". Você pode modificar e colocar qualquer nome de arquivo     
    header('Content-disposition: attachment; filename=arquivo.txt');
    //header('Content-Length: '.strlen($content));
    //header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    //header('Expires: 0');
    //header('Pragma: public');
    echo $content;
    exit;
}

HTML to create content

<form action="" method="post">
<textarea name="meuTextarea">5s6a56sa565sa65a6s56sa565sa656sa565sa656as56sa556as5as</textarea>
<p><input type="submit" value="Gerar/enviar"></p>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.