PHP 글 삭제 (DB 없이)
PHP

PHP 글 삭제 (DB 없이)

by nocagklhw 2019. 12. 30.

글 삭제를 하는 것은 의외로 써야할 코드가 별로 없다.

전 글과 비교했을 때 새로 만들면 되는 파일은 delete_process.php 이다. 

 

index.php

전 글의 코드에서 51행의 form 부분이 추가되었다. 

<?php
    function print_title() {
        if(isset($_GET['id'])) {
            echo $_GET['id'];
        } else {
            echo "Welcome";
        }
    }
    function print_description() {
        if(isset($_GET['id'])) {
        echo file_get_contents("data/".$_GET['id']);
        } else {
            echo "hihihihi";
        }
    }
    function print_list() {
        $list = scandir('./data');
            $i = 0;
            while($i < count($list)) {
                if($list[$i] != '.') {
                    if($list[$i] != '..') {
                    echo "<a href=\"index.php?id=$list[$i]\"><li>$list[$i]</li></a>\n";
                }
            }
                $i = $i + 1;
        }
    }
?>
<!DOCTYPE html> 
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?php print_title();?></title>
</head>
<body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
        <?php 
            print_list();
        ?>
    <h2>
    <?php print_title();?>
    </h2>
    </ol>
    <a href="create.php">create</a>
    <?php if(isset($_GET['id'])) {
    ?>
    <a href="update.php?id=<?=$_GET['id']?>">update</a>
    <form action="delete_process.php" method="post">
        <input type="hidden" name="id" value="<?=$_GET['id']?>">
        <input type="submit" value="delete">
    </form>
    <?php } ?>
    <h2>
        <?php print_description();?>
    </h2>
</body>
</html>

 

delete_process.php

<?php 
unlink('data/'.$_POST['id']);
header('Location: /index.php');
?>

 

 

post로 삭제 버튼을 만든 이유는?

만약 get으로 설정하게 되면 클라이언트가 아닌 사람도 그 링크로 그 사람의 글을 링크로 삭제될 수 있게 된다. 

실제 서비스에서 그런 링크가 있는 것은 매우 위험하다. 

하지만 post는 링크가 따로 생성이 되지 않으니 post로 해야 안전한 것이다. 

댓글


TOP

TEL. 02.1234.5678 / 경기 성남시 분당구 판교역로