user2557358
user2557358

Reputation:

How can I download a file with PHP or HTML?

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

Upvotes: 0

Views: 152

Answers (4)

Vijayakumar Selvaraj
Vijayakumar Selvaraj

Reputation: 523

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>

Upvotes: 0

Ignacio Ocampo
Ignacio Ocampo

Reputation: 2713

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

Upvotes: 0

Mehdi
Mehdi

Reputation: 659

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

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

Upvotes: 0

Realit&#228;tsverlust
Realit&#228;tsverlust

Reputation: 3953

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

Upvotes: 2

Related Questions