I have a script written (below) which properly displays the contents of a specific directory and creates a radio button for each file. I would like to be able to select a file and download that file to my computer.
Is this possible by changing the "action" of the form? Or is there another script or a change I need to make to my script to accomplish this?
<form name="myform" action="#" method="POST">
<?php
$dirPath = dir('./images');
$imgArray = array();
while (($file = $dirPath->read()) !== false)
{
if ((substr($file, -3)=="gif") || (substr($file, -3)=="jpg") || (substr($file, -3)=="png"))
{
$imgArray[ ] = trim($file);
}
}
$dirPat开发者_开发问答h->close();
sort($imgArray);
$c = count($imgArray);
for($i=0; $i<$c; $i++)
{
echo "<input type=\"radio\" name=\"group1\" value=\"" . $imgArray[$i] . "\">" . $imgArray[$i] . "<br />";
}
?>
</select>
<input type="submit" value="download">
I would put this at the beginning of your existing script:
if(isset($_POST['group1'])){
$f=preg_replace('/(\.\.\/?)+/','',$_POST['group1']);
if(file_exists('./images/'.$f)){
header("Content-type: ".filetype('./images/'.$f));
header('Content-disposition: attachment; filename="'.$f.'"');
echo file_get_contents('./images/'.$f);
exit;
}
}
It's my preferred way of doing what Cyclone was pointing at.
header('Location: YOURFILEDOWNLOADURL; Content-type: application/force-download');
should work, haven't tested.
Why don't you just create a download button for every file in the directory? There seems no need to use a form for this.
Remove all form HTML and change your 'for'-loop to this and you should be fine:
foreach($imgArray as $filename)
{
echo "<a href=\"./images/$filename\">Download '$filename'</a>";
echo "<br/>";
}
(since this uses foreach you can also drop the line that sets $c to count($imgArray) ).
If you insist on using a form, I suggest you either:
send the form to a parse script that reads out which file was selected, and then forwards the user to that file like how Cyclone suggests, or,
use JavaScript to directly forward the page to the selected image when the Submit-button is pressed.
Both solutions are needlessly complicated for what you are trying to accomplish, however.
精彩评论