How can I download a file with PHP or HTML?

2019-09-02 09:45发布

I am making a file hosting website and am about 95% done but have one issue. When the user clicks their file to download it, the file just appears in the browser. I need to know a way where I can define the $file variable in the while loop to be downloadable. The variable that I need to make downloadable is surrounded by asterisks(*)

LOOP:

$directory = 'uploads/' . $_SESSION['user'] . '/';

    if ($handle = opendir($directory)) {
    echo '<h3>Your files are listed below</h3>';    

    while ($file = readdir($handle)) {
        if ($file != '.' && $file != '..') {
        echo '<a href="'.$directory.'/'.$file.'">' . *$file*.'<br>';    
        }
    }
    }

4条回答
干净又极端
2楼-- · 2019-09-02 10:20

Usually every non-text file is downloaded automatically. For textfiles, you need to specify the header at the beginning of your script:

header("Content-Disposition: attachment; filename=".$file);
查看更多
Evening l夕情丶
3楼-- · 2019-09-02 10:25

You need redirect your users to a second script to handle request:

download.php?file=somepath/somefile.ext

<?php
$file_url = $_GET['file'];
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);
?>

Your link will be:

echo '<a href="download.php?file='.$directory.'/'.$file.'">' . $file.'<br>';
查看更多
Luminary・发光体
4楼-- · 2019-09-02 10:39

This will performs on onclick, with confirmation alert box,

<?php

$directory = 'uploads/' . $_SESSION['user'] . '/';

if(isset($_REQUEST['DelFile'])) {
    $DeleteFile = $_REQUEST['DelFile'];
    if(file_exists($directory.$DeleteFile)) {
        @unlink($directory.$DeleteFile);
        header("location:SamePageURL.php?msg=1");
    } else header("location:SamePageURL.php?msg=2");
}

if ($handle = opendir($directory)) {
echo '<h3>Your files are listed below</h3>';    
    while ($file = readdir($handle)) {
        if ($file != '.' && $file != '..') {
            echo '<a target="_blank" href="'.$directory.'/'.$file.'">' . $file.' <a href="javascript:deletedata('.$file.')>Delete</a> <br>';  
        }
    }
}

if(isset($_REQUEST['msg'])) {
    $Message = $_REQUEST['msg'];
    if($Message == 1) echo "File deleted sucessfully";
    else if($Message == 1) echo "File not found";
}
?>
<script type="text/javascript">function deletedata(FileName){if(window.confirm("Wish to Delete (Press OK) or Cancel"))  window.location="SamePageURL.php?DelFile="+FileName;}</script>
查看更多
smile是对你的礼貌
5楼-- · 2019-09-02 10:44

the issue is header, check the link for more information:

http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

查看更多
登录 后发表回答