简体   繁体   中英

HTML/PHP : open download text file box on button click

I tried to find something for this with no success... I simply want to create a content and let the user download it in a text file, by clicking on a button which would open a classic download box.

I have my html button :

echo "<form name=\"myform\" action=\"myfile.php\" method=\"POST\" enctype=\"multipart/form-data\">";
echo "<input type=\"hidden\" name=\"phase2\" value=\"1\">";
echo "<div class=\"siej_upload_field\"><input type=\"submit\" name=\"submit\" value=\"Save file\"></div>";

And the call after a click :

if( isset($_POST['phase2']) && $_POST['phase2']== 1)
{
    $file = 'mytextfile.txt';
    $content = 'content test';
    $res = file_put_contents($file, $content);
    echo 'result : '. $res . '<br/>';
}

But nothing happens although I correctly enter this condition. I get this result:

result : 12

So what to do? Thanks for your help...

Try this.

<?php
        $file = 'mytextfile.txt'; #Place of the file or the post.

        if (file_exists($file)) 
        {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            readfile($file);
            exit;
        }
    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM