简体   繁体   中英

How to download a file in PHP when clicking submit input button

I have a form with an input submit button, and want it so that when the button is clicked, it downloads a file.

My if statement basically just checks the file exists, and if so starts to download the file. That part works, however I can't get it to work so that it downloads the file ONLY when the button is clicked.

At the moment, nothing happens when the button is clicked.

Maybe I'm not putting the if statement in the correct place?

      <form action='?module=clientsupport&call=landing-proco' method='post' enctype="multipart/form-data">           
        <input type='submit' name='download' class="button yellow" value="Download"/>

        <?php
        if (file_exists("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt")) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt") . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt"));
            readfile("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt");
            sleep(2);
            unlink("D:/wwwroot/Workspace/George/Goliath/modules/test/file.txt");
            exit;
        }
        ?>

    </form>

Remove php code from html, create new file with your PHP code and link action of your form to this file. It will work fine

Look at your program.

Line 1:

  <form action='?module=clientsupport&call=landing-proco' method='post' enctype="multipart/form-data"> 

… starts outputting an HTML document.

Then you get to:

  header('Content-Description: File Transfer'); 

where you start to output something that isn't an HTML document, but it is too late because you are already in the middle of an HTML document .

Design your logic to output one thing or the other.

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