Reputation: 11
I'm trying to list the content of a specific directory as links and want the browser to open or download the files if I click on them, as it normaly would do like a default html file-link, but the links are not working, if I click. If I right-click and copy the link and paste to a new tab, it opens the file.
My code:
<?php
$dir = 'c:/dir/work';
$files = scandir($dir);
$filecount = count($files);
for ($i=0; $i <= $filecount ; $i++) {
if ($files[$i] != '.' && $files[$i] != '..') {
echo '<p><a href="' . $dir . '/' . $files[$i] . '">' . $dir . '/' . $files[$i] . '</a></p>';
}
}
?>
Upvotes: 1
Views: 5837
Reputation: 11
Thanks for the replys. I tried them, but did not work for me. I think I miss the basics for this. Finaly I figured out something else:
// LIST FILES FROM UPLOADS/SUBDIR BY DAY-ID
function list_files_from_subdir ($subdir, $day_id) {
$upload = wp_upload_dir ();
$dir = $upload[basedir] . $subdir;
$url = $upload[baseurl] . $subdir;
$files = scandir($dir);
$filecount = count($files);
for ($i=0; $i <= $filecount ; $i++) {
$fileday = substr($files[$i], 0, 8);
if ($day_id == $fileday) {
echo '<p><a href="' . $url . $files[$i] . '" target="_blank">' . $files[$i] . '</a></p>';
}
}
}
Upvotes: 0
Reputation: 518
Please have a look suggested code for auto download file when click on generated link.
<?php
$dir = 'c:/dir/work';
$files = scandir($dir);
$filecount = count($files);
for ($i=0; $i <= $filecount ; $i++) {
if ($files[$i] != '.' && $files[$i] != '..') {
echo '<p><a href=?file=' . $dir . $files[$i] . '>' . $dir . '/' . $files[$i] . '</a></p>';
}
}
if(isset($_GET['file'])){
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($_GET['file']) . "\"");
readfile($_GET['file']);
}
?>
Upvotes: 1
Reputation: 1524
You ought to have a central processing script for all the files you want to download. So your href will point to the script instead of file itself like this:
echo '<p><a href="downloadfile.php?path=' . $dir . '/' . $files[$i] . '">' . $dir . '/' . $files[$i] . '</a></p>';
And in this script, you need to send content-disposition header for the files to get download, instead of being displayed inline, like this:
header('Content-Disposition: attachment; filename='.$_GET['path']);
Hope this helps.
Upvotes: 0