0

I have the following code which kind of works but for some reason the $download includes the part inside into the downloaded file.

<form method="post">
<button id="click" name="click">Download</button>
</form>

<?php
if(isset($_POST['click'])){
$files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
$download = $newest_file;

header("Content-Type: text/plain");
header('Content-Disposition: attachment; filename="'.$download.'"');
readfile("/local/path/$download");
}
?>

Downloaded file

form method="post">
<button id="click" name="click">Download</button>
</form>

Start-of-the-actual-log
blabla
blabla
blabla

What is causing this to happen? I only want to download the newest file in a folder.

2
  • 2
    In your code, you specifically output that HTML at the top of the script. Commented Jul 10, 2020 at 8:51
  • @NigelRen I'm sorry, I'm pretty much a noob. My understanding of the code is that it scans the local path and then grabs the file. I'm not sure how it is including the HTML part. Commented Jul 10, 2020 at 8:58

1 Answer 1

1

Dont print anything or send header before downloading, look at this :

<?php
if(isset($_POST['click'])){
    $files = scandir('/local/path', SCANDIR_SORT_DESCENDING);
    $newest_file = $files[0];
    $download = $newest_file;

    header("Content-Type: text/plain");
    header('Content-Disposition: attachment; filename="'.$download.'"');
    readfile("/local/path/$download");
}else{
     echo'
     <form method="post">
         <button id="click" name="click">Download</button>
     </form>';
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Putting the code (without the else statement) serves just the file. But I still don't understand why the HTML gets included in the download to being with.

Your Answer

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.