Skip to content Skip to sidebar Skip to footer

Php Download Button Not Working Generate Empty File

I have two button in the form, one is to submit and second button download the output shown in the textarea. The submit works fine but download button create empty file and does n

Solution 1:

You have to generate the output also if downloading (unless you take it from the second textarea), so use if(isset($_POST["submit"]) || isset($_POST["download"]) ) in the test, instead of only if(isset($_POST["submit"]))

The final code would look like this:

<?php

error_reporting(0);
$mytext = "";

$txt = preg_replace('/\n+/', "\n", trim($_POST['inputtext']));
$text = explode("\n", $txt);
$output  = array();


/* CHANGED HERE */if(isset($_POST["submit"]) || isset($_POST["download"]) ) {


    for($i=0;$i<count($text);$i++) {

        $output[] .= trim($text[$i]) . ' Text added with output'.PHP_EOL;

    }

}


if(isset($_POST["download"]) ) {

    $handle = fopen("file.txt", "w");
    fwrite($handle, implode("\r",$output));
    fclose($handle);

    header('Content-type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename('file.txt'));
    header('Expires: 0');
    ob_end_clean();
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('file.txt'));
    readfile('file.txt');
    exit;
}   

?><formmethod="POST"action="test.php"><textareaname="inputtext"rows="10"cols="100"placeholder="Enter Any Text!"required><?phpif(!empty($_POST["inputtext"])) { echo$_POST["inputtext"]; } ?></textarea><br><br><inputtype="submit"name="submit"value="Do it!"><br><br><p>Output goes here. </p><textareaname="oputputtext"rows="10"cols="100" ><?phpecho implode($output);?></textarea><inputtype="submit"name="download"value="Download Output"></form>

Post a Comment for "Php Download Button Not Working Generate Empty File"