How can I download a file with PHP or HTML?

守給你的承諾、 提交于 2019-12-11 15:12:52

问题


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>';    
        }
    }
    }

回答1:


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>



回答2:


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);



回答3:


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

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




回答4:


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>';


来源:https://stackoverflow.com/questions/20605867/how-can-i-download-a-file-with-php-or-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!