简体   繁体   English

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

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

I've figured out how to make an array of each of my posts so that the txt file is unique, but I'm stuck on trying to figure out how to delete it. 我已经弄清楚了如何对每个帖子进行排列,以使txt文件是唯一的,但是我一直在试图弄清楚如何删除它。 This is my progress so far: 到目前为止,这是我的进步:

Index.php: 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: Deletepost.php:

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

?>

I know I have to use $_REQUEST['filename']; 我知道我必须使用$ _REQUEST ['filename']; somewhere in deletepost.php, but that's as far as I've gotten. 在deletepost.php中的某处,但是据我所知。 Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

You are looking for unlink function. 您正在寻找取消链接功能。 You can add this logic : 您可以添加以下逻辑:

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

But I strongly advise you to check and recheck the $filename value, and see if the file to delete is not sensible (ex : http://yoursite.com/deletepost.php?filename=../index.php will delete your index.php file !) 但我强烈建议您检查并重新检查$ 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