How can I download a file outside web directory using PHP without appending HTML content to file?
<p>I am having trouble writing a single PHP script that displays an HTML text-box that will search for a file in the /tmp directory of a Linux machine.  Once the user types the string into the text box and presses the submit button, matching hyperlinks will be presented underneath the textbox with names of the files outside the web directory (in /tmp).</p>

<p>When I click the hyperlink, I want to download the file from the /tmp directory.  Unfortunately, because I need to use a single php script, HTML content is being appended to the file since I am using the php header command.   </p>

<p>Is there any way I can download the file without having html from my php page appended to the file and without using more than a single php script? </p>

<pre><code>&lt;?php


function displayfiles()
{
    echo '&lt;ul&gt;';

    if ($handle = opendir('/tmp')) 
    {
        while ($file = readdir($handle))
        {
            if ($file != "." &amp;&amp; $file != ".." &amp;&amp; (strstr($file, $_POST['searchbox'])))
            {
                echo '&lt;li&gt;&lt;a href="search.php?file='.$file.'"&gt;'.$file.'&lt;/a&gt;&lt;/li&gt;';
            }
            else if ($file != "." &amp;&amp; $file != ".." &amp;&amp; (eregi($file, $_POST['searchbox'])))
            {
                echo '&lt;li&gt;&lt;a href="search.php?file='.$file.'"&gt;'.$file.'&lt;/a&gt;&lt;/li&gt;';  
            }
        }
        closedir($handle);
    }
    echo '&lt;/ul&gt;';
}

function downloadfile($filename)
{            
    header("Content-disposition: attachment; file='/tmp/$filename' filename=$filename");
        header("Content-Length: " . filesize("/tmp/$filename"));
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile("/tmp/$filename");
    exit(); 
}


echo 
"&lt;html&gt;
&lt;head&gt;
&lt;title&gt;File Search&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
        &lt;form method='POST'&gt;
        &lt;input id='searchbox' name='searchbox' id='searchbox' type='textbox' /&gt;
        &lt;input type='submit' name='submit' /&gt;
        &lt;/form&gt;";

                if (isset($_POST['submit']))
                {
                    displayfiles();        
                }
                else if (isset($_GET['file']) &amp;&amp; file_exists("/tmp/".$_GET['file']))
                {
            downloadfile($_GET['file']);
        }

 echo "&lt;/body&gt;&lt;/html&gt;";
?&gt;
</code></pre>
