PHP从下拉列表中删除文件

时间:2015-03-10 05:05:43

标签: php html

我有一个下拉列表,其中填充了使用下面列出的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) {[&#34;行动&#34;] =&gt; string(6)&#34;删除&#34; }

2 个答案:

答案 0 :(得分:1)

您的表单不会使用

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

尝试

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

答案 1 :(得分:1)

您需要使用form标记包装代码。此外,$ _POST需要获取您的选择的名称(在这种情况下),所以:

<强> form.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"){
      ...
  }
?>