Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing string to file and force download in PHP [closed]

Tags:

php

I'm looking into methods of how to create a file from a string, this could be plain text would save as .txt and php as .php etc but I was hoping to get some insight into it

**I found this code

$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);

But would I need to have people.txt saved on my server?

The force download part

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($File));
header("Connection: close");

Where would I need to house the above, I'm assuming the code is right to force download my ready made file?

like image 559
ngplayground Avatar asked Feb 25 '13 09:02

ngplayground


People also ask

How Force download file from remote server PHP?

Use the readfile() function with application/x-file-to-save Content-type header, to download a ZIP file from remote URL using PHP. header("Content-type: application/x-file-to-save"); header("Content-Disposition: attachment; filename=". basename($remoteURL));

How do you download the contents of a one PHP script into another?

filesize($user. $format)); readfile($user. $format); php.

How do I create a .TXT file in PHP?

PHP Create File - fopen() The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

How we create and download folder with PHP?

The download. php: <? php $name= $_GET['nama']; download($name); function download($name) { $file = $nama_fail; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.


1 Answers

You do not need to write the string to a file in order to send it to the browser. See the following example, which will prompt your UA to attempt to download a file called "sample.txt" containing the value of $str:

<?php

$str = "Some pseudo-random
text spanning
multiple lines";

header('Content-Disposition: attachment; filename="sample.txt"');
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient
header('Content-Length: ' . strlen($str));
header('Connection: close');


echo $str;
like image 127
TML Avatar answered Oct 03 '22 17:10

TML