Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a text file and force to download with php

Tags:

Im using a button to direct to a script which creates a text file:

<?php $handle = fopen("file.txt", "w"); fwrite($handle, "text1....."); fclose($handle); ?> 

after that I want the web browser to propose to download or open this file how should I do? Thanks

like image 850
stevey Avatar asked Aug 10 '12 14:08

stevey


People also ask

How do I force a file to download?

On your computers desktop, right click on the item. Choose the 'Send to' option and then choose 'Compressed (zip) folder'. This will place your download in a zip folder. When attaching your downloadable item, choose the one that has been placed in the zip folder.

How can I force download a zip file in PHP?

For force download, you have to set the header correctly. When you are setting the header for download the Zip file that time <coce>Content-type and Content-Disposition correctly. In Content-Disposition , add the attachment, it will suggest the browser to download the file instead of displaying it directly.

How can you display a file download dialog box using PHP?

Show activity on this post. $filename = $_GET['movie']; //Get the filename if(is_file($filename)) { //If you want to read and output the contents do it here header('Content-disposition: attachment; filename='. $filename); } exit();


2 Answers

use readfile() and application/octet-stream headers

<?php     $handle = fopen("file.txt", "w");     fwrite($handle, "text1.....");     fclose($handle);      header('Content-Type: application/octet-stream');     header('Content-Disposition: attachment; filename='.basename('file.txt'));     header('Expires: 0');     header('Cache-Control: must-revalidate');     header('Pragma: public');     header('Content-Length: ' . filesize('file.txt'));     readfile('file.txt');     exit; ?> 
like image 189
Mihai Iorga Avatar answered Oct 12 '22 11:10

Mihai Iorga


$content = file_get_contents ($filename); header ('Content-Type: application/octet-stream'); echo $content; 

Should work

like image 36
Edson Medina Avatar answered Oct 12 '22 12:10

Edson Medina