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).
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.
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?
<?php
function displayfiles()
{
echo '<ul>';
if ($handle = opendir('/tmp'))
{
while ($file = readdir($handle))
{
if ($file != "." && $file != ".." && (strstr($file, $_POST['searchbox'])))
{
echo '<li><a href="search.php?file='.$file.'">'.$file.'</a></li>';
}
else if ($file != "." && $file != ".." && (eregi($file, $_POST['searchbox'])))
{
echo '<li><a href="search.php?file='.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}
echo '</ul>';
}
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
"<html>
<head>
<title>File Search</title>
</head>
<body>
<form method='POST'>
<input id='searchbox' name='searchbox' id='searchbox' type='textbox' />
<input type='submit' name='submit' />
</form>";
if (isset($_POST['submit']))
{
displayfiles();
}
else if (isset($_GET['file']) && file_exists("/tmp/".$_GET['file']))
{
downloadfile($_GET['file']);
}
echo "</body></html>";
?>
You need to handle the output of the file-download before outputting anything else, quick and dirty example (even only with one function instead of two as suggested in the comment, I think you get the idea):
Also take care that there can be data inside
/tmp/that should not be offered for download as it can be used to attack applications, their users or even the system.