PHP 从下拉列表中删除文件


PHP Delete File from Dropdown

我有一个下拉列表,其中填充了使用下面列出的 PHP 从目录中提取的文件,并试图弄清楚如何在选择它们时使用表单中的删除按钮删除它们。

<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection"  id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList">
<?php
   $directory = $directory = 'users/' . $_SESSION['username'];
   $filesContents = Array();
   $files = scandir( $directory ) ;
   foreach( $files as $file )
  {
   if ( ! is_dir( $file ) )
  {
   $filesContents[$file] = file_get_contents($directory , $file);
  echo "<option>" . $file . "</option>";
  }
   }
   ?>
   </select>

随时更新代码。

<?php
   session_start();
    $directory = $directory = $_SERVER['DOCUMENT_ROOT'] . '/users/' . $_SESSION['username'];
    $file_to_delete = $_POST['CodeList'];
    if ( unlink ($directory.'/'.$file_to_delete) ) {
      echo $file_to_delete . " deleted.";
   } else {
echo "Error.";
}
?>

编辑和更新的代码

现在说警告:unlink(/myhome/root/public_html/users/Addiction/) [function.unlink]:第 5 行的/home/revo/public_html/evo/avdeleteprocess.php 中没有这样的文件或目录错误。

所以它找到了正确的文件夹,只是没有从下拉列表选择中找到文件。

还编辑了添加,我在删除脚本之后立即运行了一个var_dump($_POST)以查看它作为 POST 值提取的内容,结果为:Error.array(1) { ["Action"]=> string(6) "删除" }

您需要使用 form 标记包装代码。此外,$_POST 需要获取您选择的名称(在本例中),因此:

形式.php:

<form action="avdeleteprocess.php" method="post">
<select size="1" name="CodeList" id="CodeList">
<?php
   $directory = 'users/' . $_SESSION['username'];
   $filesContents = Array();
   $files = scandir( $directory ) ;
   foreach( $files as $file )
  {
   if ( ! is_dir( $file ) )
  {
   $filesContents[$file] = file_get_contents($directory , $file);
  echo "<option value='".$file."'>" . $file . "</option>";
  }
   }
   ?>
   </select>
   <input type="submit" name="Action" value="DELETE" />
</form>

avdeleteprocess.php:

<?php
  session_start();
  $directory = 'users/'.$_SESSION['username'].'/';
  //here you can even check if user selected 'delete' option:
  if($_POST['Action'] == "DELETE"){
      $file_to_delete = $_POST['CodeList'];
      if(unlink($directory.'/'.$file_to_delete))
         echo $file_to_delete." deleted.";
      else
         echo "Error deleting file ".$file_to_delete;
  }
  if($_POST['Action'] == "SAVE"){
      ...
  }
?>

您的表格将不会使用

<button type="button">Delete</button>

尝试

<button type="submit">Delete</button>