r0uder r0uder - 4 months ago 18
PHP Question

Links to download\delete from a directory

I have upload and download scripts. Here they are:

Upload

<html>
<head>
<title> Result </title>
</head>
<body>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<link rel="stylesheet" href="stylesheet.css">
<div class="container">
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<pre>';


if (!empty($_FILES) && move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File was succesfully uploaded to ".$uploaddir;
} else {
echo "Something went wrong. Attach you file, please. \n";
}


//
//if ($_FILES["userfile"]["size"] > 500000) {
// echo "Sorry, your file is too large.\n";
//}

$filelist = scandir($uploaddir, 1);

?>
<p> Download your files: </p>

<table>
<?php foreach($filelist as $file): ?>
<tr>
<td> <?php echo $file; ?></td>
</tr>
<?php endforeach; ?>
</table>

<?php
//debug
// print_r ($filelist);
// print_r($_FILES);
?>
</div>
</body>
</html>


Download

<?php

// block any attempt to the filesystem
if (isset($_GET['file']) && basename($_GET['file']) == $_GET['file']) {
$filename = $_GET['file'];
} else {
$filename = NULL;
}


$error = 'Sorry, the file you are requesting is unavailable for ya.';

if (!$filename) {
// if $filename is NULL or false display the message
echo $error;
} else {
$path = '/var/www/uploads/'.$filename;
if (file_exists($path) && is_readable($path)) {
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// display the error messages if the file canĀ“t be opened
$file = @ fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $error;
}
} else {
echo $error;
}
}


Now I can see just the list of the files I uploaded.

Like that

I want to make them links so I can download and delete (using GET and unlink) each file from the directory. I assume I have to use foreach but I still can't figure it out. Thanks in advance.

Answer

Just make them links:

<?php foreach($filelist as $file): ?>
    <tr>
        <td>
          <a href="download.php?file=<?php echo $file; ?>"><?php echo $file; ?></a>
        </td>
    </tr>
<?php endforeach; ?>