Reputation: 147
I am listing the files from a directory with scandir function and displaying the names in a table row . My question is how to make the listed files downloadable links and how to remove the first two rows which aren't file names which are '.' and '..' ?
Here is my code:
$result = scandir('test');
<table border = "1">
<?php
foreach($result as $value){
echo "<tr>
<td>$value</td>
</tr>";
}
?>
</table>
Upvotes: 0
Views: 59
Reputation: 3434
If you want to force the download you should try this code:
<?php
$dir = "test";
$result = scandir($dir);
?>
<table border = "1">
<?php
foreach($result as $value){
if(strlen(str_replace('.','',$value)) > 0)
{
echo '<tr>
<td><a target="_blank" href="download.php?file='.base64_encode($dir."/".$value).'">'.$value.'</a></td>
</tr>';
}
}
?>
</table>
Create also a download.php
file where you paste the force-download code below:
<?php
$file_url = base64_decode($_GET['file']);
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
?>
Upvotes: 1
Reputation:
Edit your code to
$result = scandir('test');
<table border = "1">
<?php
foreach($result as $value){
if($value == "." OR $value == ".."){continue;}
echo "<tr>
<td><a href='download.php?value=".$value."'>".$value."</a></td>
</tr>";
}
?>
</table>
Create file download.php and put inside it the following code:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_GET['value']);
finfo_close($finfo);
$size = filesize($_GET['value']);
header("Content-Type: ". $mime);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $_GET['value']);
echo file_get_contents($_GET['value']);
?>
This will allow you to automatically download every type of file, including, for example .html. If you're looking for something to download files that browser can't understand, answer of @maskacovnik is the one that suits most to this situation.
Upvotes: 1
Reputation: 3084
$result = scandir('test');
<table border = "1">
<?php
foreach($result as $value){
if($value == ".." || $value == ".") continue;
echo '<tr><td><a href="test\\'.$value.'">'.$value.'</a></td></tr>';
}
?>
</table>
Upvotes: 0