0

On my website I have a JavaScript function that using PHP function creates a file locally on my server (same directory as the website files). The name of this file is known only to these JavaScript and PHP functions. I want to open a regular 'Save As' box to the user to download this file. Is there a way to do this using Javascript/PHP in a manner that will work for Firefox, Chrome and Explorer/Edge? (Only the Javascript/PHP know the file name)

This is the PHP example:

file_put_contents($filename,$txt);
header('content-type: application/text');
header('content-disposition: attachment; filename=' . $filename);
readfile($filename);
asked Oct 25, 2016 at 11:26

1 Answer 1

2

In chrome & firefox it saves automatically and in IE a window opens so if a user has not changed their settings by default will they see the where to save dialog regardless of the browser they're using. go to

https://support.google.com/chrome/answer/95574?hl=en-GB

For more information. You can use php code for downloading the file from your server.

header('content-type: application/[type]');
header('content-disposition: attachment; filename=yourfile.file-extension');
readfile('yourfile.file-extension');

for a large file, you can use

function readfileChunked($filename, $retbytes=true){
 $chunksize = 1*(1024*1024);
 $buffer = '';
 $cnt = 0;
 $handle = fopen($filename, 'rb');
 if ($handle === false) {
 return false;
 }
 while (!feof($handle)) {
 $buffer = fread($handle, $chunksize);
 echo $buffer;
 ob_flush();
 flush();
 if ($retbytes) {
 $cnt += strlen($buffer);
 }
 }
 $status = fclose($handle);
 if ($retbytes && $status) {
 return $cnt; // return num. bytes delivered like readfile() does.
 }
 return $status;
 }
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. get_remote_size($url) );
header('Connection: close');
readfileChunked( $url );
answered Oct 25, 2016 at 11:35
Sign up to request clarification or add additional context in comments.

2 Comments

Using this code, the file (.txt) content is displayed in the webpage itself instead of being downloaded as a file...
@JohnEllis See the answer I have changed.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.