链接从目录下载\删除

问题描述:

我有上传和下载脚本。在这里,他们是:链接从目录下载删除

上传

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

下载

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

现在我可以看到只是我上传的文件列表。

Like that

我要让他们链接这样我就可以下载和删除(使用GET和取消链接)从目录中的每个文件。我认为我必须使用foreach,但我仍然无法弄清楚。提前致谢。

+0

有些东西似乎离你的代码。您标记为“上传”的第一个片段不包含用于上传文件的表单,但它包含由“下载您的文件:”并由“foreach”循环生成的文件列表。第二个标记为“下载”的代码片段似乎与下载有关,但与用户的交互方式并不明显。这两个片段都不清楚。也许你可以简化你的代码并显示更多的上下文? – Julian

只是让他们链接:

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

谢谢,这很容易:) – r0uder