r0uder r0uder - 1 year ago 57
PHP Question

Links to download\delete from a directory

I have upload and download scripts. Here they are:


<title> Result </title>
<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">
$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>

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

// print_r ($filelist);
// print_r($_FILES);



// 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
} 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 Source

Just make them links:

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