PHP-How to solve that Html Page Source is appending to the download file
<p>I am downloading a file from Ftp folder after upload.</p>

<p>Problem is when i open the txt file it show s html page source appending with file content</p>

<p>If i preview image file(jpg or jpeg) it shows image is corrupted</p>

<p>If i open pdf error: Failed to load Pdf document</p>

<p>Please let me know where i am wrong.</p>

<p>Here is my code:</p>

<pre><code>if (isset($_GET['id']) &amp;&amp; basename($_GET['id']) == $_GET['id']) {
    $filename = $_GET['id'];
} else {
    $filename =NULL ;
}

$err = 'Sorry, the file you are requesting is unavailable.';
if (!$filename) {
    // if variable $filename is NULL or false display the message
    echo $err;
} else {
    // define the path to your download folder plus assign the file name
    $path = '/home/devestctrl/public_html/wp-content/uploads/'.$filename;
    // check that file exists and is readable
    if (file_exists($path) &amp;&amp; is_readable($path)) {
        // get the file size and send the http headers
        $size = filesize($path);
        header('Content-Type: application/octet-stream');
        header('Content-Type: '.$mime);
        header('Content-Length: '.$size);
        header('Content-Disposition: attachment; filename='.$filename);
        header('Content-Transfer-Encoding: binary');
        // open the file in binary read-only mode
        // display the error messages if the file can´t be opened
        $file = @ fopen($path, 'rb');
        if ($file) {
            // stream the file and exit the script when complete
            fpassthru($file);
            exit();
        } else {
            echo $err;
        }
    } else {
        echo $err;
    }
}
</code></pre>

<p>I checked by using echo of <code>$filename</code>; </p>

<p>It shows the output in the file instead of printing in page.</p>

<p>error displays: </p>

<blockquote>
  <p>Sorry, the file you are requesting is unavailable.</p>
</blockquote>

<p>After error also i can download, but echoed <code>$filename</code> displayed in file. </p>

<p>Insert into table:</p>

<pre><code> echo "&lt;tr&gt;&lt;a href='?id=" . $row["FileupName"]. "'&gt;".$row["FileupName"]."&lt;/td&gt;&lt;/tr&gt;";
</code></pre>