繁体   English   中英

如何使用php删除特定的txt文件

[英]How to delete a specific txt file using php

我已经弄清楚了如何对每个帖子进行排列,以使txt文件是唯一的,但是我一直在试图弄清楚如何删除它。 到目前为止,这是我的进步:

index.php文件:

      <?php

    $fileNames = glob("*.txt");
    $posts = array();

    foreach($fileNames as $fileName) {
      $post = file($fileName);
      array_push($posts, $post);
    }

    $postNum = 0;
    foreach($posts as $post) {

      $i = 1;
      $fname = $fileNames[$postNum];
      foreach($post as $line) {

        if ($i==1) {
          echo "<h1 style=\"padding: 0px 30px 0px 30px;\">$line</h1>";
        } else {
          echo "<p style=\"padding: 0px 30px 0px 30px; color:#4d4d4d;\">$line</p>";
          echo "<form action=\"deletepost.php\" method=\"get\" style=\"padding: 0px 30px 0px 30px;\"><input type=\"submit\" value=\"Delete Post\"><input type='hidden' name='filename' value='".$fname."'></form>";
        }
        $i++;
      }



      $postNum++;

    }


  ?>

Deletepost.php:

    <?php
session_start();
    if($_SESSION['authenticated'] != true) {
        header("Location: login.php");
        die();
    }

?>

我知道我必须使用$ _REQUEST ['filename']; 在deletepost.php中的某处,但是据我所知。 任何帮助表示赞赏。 谢谢。

您正在寻找取消链接功能。 您可以添加以下逻辑:

Deletepost.php:

<?php
    session_start();
    if($_SESSION['authenticated'] != true || !isset($_GET['filename'])) {
        header("Location: login.php");
        die();
    }

    $filename = $_GET['filename'];

    if(file_exists($filename)) {
        unlink($filename);
    }
?>

但我强烈建议您检查并重新检查$ filename值,并查看要删除的文件是否不合理(例如:http: //yoursite.com/deletepost.php? filename= ../index.php会删除您的index.php文件!)

您可以在PHP中使用unlink()删除文件,如果成功则返回true,否则返回false。

    if (file_exists($_REQUEST['filename']) unlink($_REQUEST['filename']);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM