2011-06-11 158 views
0

我有以下的HTML表单:PHP文件删除问题?

<form action='delete.php' method='POST'> 
    <table> 
     <div class = '.table'> 
      <?php 
      $dir = '../uploads/store/'; 
      $newdir = ereg_replace('\.','',$dir); 

      if (is_dir($dir)) { 
       if ($dh = opendir($dir)) { 
        while (($file = readdir($dh)) !== false) { 
        if (!preg_match('/^(\.(htaccess|\.)?|index\.html)/',$file)) { 
         echo "<tr><td><font color = 'white'><a href='$newdir$file'>$file</a></font></td>"; 
         echo "<td><input type='submit' value ='Delete'></td></tr>"; 
         echo "<input align='right' type='hidden' value='$file' name='file'>"; 
        } 
        } 
        closedir($dh); 
       } 
      } 
      ?> 
     </div> 
    </table> 
</form> 

哪些链接下面的PHP脚本:

<?php 
    session_start(); 

    $file = $_POST['file']; 
    $dir = '../uploads/store/'; 
    $file = $dir . $file; 

    opendir($dir); 

    if(unlink($file)) { 
     echo "File sucessfully deleted"; 
     $_SESSION['username'] = 'guitarman0831'; 
     header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html'); 
    } else { 
     echo "Error: File could not be deleted"; 
     $_SESSION['username'] = 'guitarman0831'; 
     header('Refresh: 2;url=http://www.ohjustthatguy.com/uploads/uploads.html'); 
    } 

?> 

然而,当在HTML表单按下了删除键,一个以上的项目预期删除被删除。

希望这是有道理的。

注意:我不打算为这些脚本安全,我将在稍后处理。现在只有我使用这项服务。

回答

2

您的HTML表单需要通过各种提交按钮传递$file的值,而不是使用隐藏字段。

问题是,所有隐藏字段都会在提交表单时发送到delete.php。然后,由于您没有使用PHP友好的HTML数组变量语法,因此PHP仅使用最后一个设置值$_POST['file']。如果您在delete.php中执行的$_POST,您将看到POST输入是什么。

最简单的方法就是将每个提交按钮命名为file,并将$ file作为其value。即你可以这样做:

<button name="file" value="example.txt" type="submit">Delete</button> 

或者,你可以使用单选按钮或其他标记。

+1

p.s.所写的脚本是不安全的。它受到目录遍历攻击,CSRF ...始终验证您的输入! [realpath](http://php.net/manual/en/function.realpath.php)是你的朋友。 – joelhardi 2011-06-11 04:30:48

+0

不起作用,错误:“警告:取消链接(../ uploads/store /)[function.unlink]:是一个目录” – Jason 2011-06-11 04:31:39

+0

没关系它的工作,谢谢! – Jason 2011-06-11 04:36:17