简体   繁体   中英

download file from a folder using php

I need to download csv file from export folder which is inside the www folder.
I could make it as link, but by attempting to save as the csv files, an empty csv file will be downloaded. Any idea?

<?php
$dir_open = opendir('./export');

while(false !== ($filename = readdir($dir_open))){
if($filename != "." && $filename != ".."){
    $link = "<a href='./$filename'> $filename </a><br />";

    echo $link;
}
}
closedir($dir_open);
?>

the result links are like:
在此处输入图片说明

by right clicking and selecting save link as, an empty csv file is downloaded

Try this one which i used this. Ex: download.php

<?php
if(isset($_GET['link']))
{
    $var_1 = $_GET['link'];

    $dir = "export/"; 
    $file = $dir . $var_1;

    if (file_exists($file))
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
       ob_clean();
       flush();
       readfile($file);
       exit;
    }
} 
?>

I used a link like this

$link = "<a href='download.php?link=$filename'> $filename </a><br />";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM