보안을 그리다, 훈이

[Web Hacking / PHP & MySQL] 게시판 구현 - Websites for Members 본문

Programming/PHP & MySQL

[Web Hacking / PHP & MySQL] 게시판 구현 - Websites for Members

HooNeee 2021. 5. 3. 18:52

앞서 회원가입, 로그인, 로그아웃 기능을 모두 구현하고 보니, 본 게시판은 회원전용 게시판으로서의 대대적인 수정이 필요했다.

(과장 좀 했는데 끝내고보니 별거 아닌듯ㅎ)

 

먼저 살펴볼 페이지는 글을 작성하고 게시하는 write.php / write_action.php이다.

기존의 UI를 보면 제목, 내용과 함께 작성자, 비밀번호를 작성하도록 되어있는데, 이제는 게시글을 읽는 것 외에는 완전히 회원전용 게시판이므로 사용자의 세션을 통해 모든 것을 관리하게 된다.

따라서 작성자, 비밀번호 입력란을 삭제하고, 마찬가지로 db_board 데이터베이스 내 board 테이블의 비밀번호 컬럼 또한 삭제해주었다.

작성자는 자동으로 세션 아이디값을 넣어두게끔 처리했다.

 

 

[write.php 개선 소스코드]

<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>
    <style>
        table.table2 {
            border-collapse: separate;
            border-spacing: 1px;
            text-align: left;
            line-height: 1.5;
            border-top: 1px solid #ccc;
            margin: 20px 10px;
        }

        table.table2 tr {
            width: 50px;
            padding: 10px;
            font-weight: bold;
            vertical-align: top;
            border-bottom: 1px solid #ccc;
        }

        table.table2 td {
            width: 100px;
            padding: 10px;
            vertical-align: top;
            border-bottom: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <?php
    session_start();
    $URL = "./login.php";
    if (!isset($_SESSION['userid'])) {
    ?>

        <script>
            alert("로그인이 필요합니다.");
            location.replace("<?php echo $URL ?>");
        </script>
    <?php
    }
    ?>

    <form method="post" action="write_action.php">
        <!-- method를 get -> post로 바꿔야됨!! -->
        <table style="padding-top:50px" align=center width=auto border=0 cellpadding=2>
            <tr>
                <td style="height:40; float:center; background-color:#3C3C3C">
                    <p style="font-size:25px; text-align:center; color:white; margin-top:15px; margin-bottom:15px"><b>게시글 작성하기</b></p>
                </td>
            </tr>
            <tr>
                <td bgcolor=white>
                    <table class="table2">
                        <tr>
                            <td>작성자</td>
                            <td><input type="hidden" name="name" value="<?= $_SESSION['userid'] ?>"><?= $_SESSION['userid'] ?></td>
                        </tr>

                        <tr>
                            <td>제목</td>
                            <td><input type="text" name="title" size=87></td>
                        </tr>

                        <tr>
                            <td>내용</td>
                            <td><textarea name="content" cols=75 rows=15></textarea></td>
                        </tr>
                        <!-- 비밀번호 입력란 제거 -->
                    </table>

                    <center>
                        <input style="height:26px; width:47px; font-size:16px;" type="submit" value="작성">
                    </center>
                </td>
            </tr>
        </table>
    </form>
</body>

</html>

 

 

[write_action.php 개선 소스코드]

<?php
$connect = mysqli_connect("127.0.0.1", "root", "password", "db_board") or die("fail");

$id = $_POST['name'];                   //Writer
$title = $_POST['title'];               //Title
$content = $_POST['content'];           //Content
$date = date('Y-m-d H:i:s');            //Date

$URL = './index.php';                   //return URL


$query = "INSERT INTO board (number, title, content, date, hit, id) 
        values(null,'$title', '$content', '$date', 0, '$id')";


$result = $connect->query($query);
if ($result) {
?> <script>
        alert("<?php echo "게시글이 등록되었습니다." ?>");
        location.replace("<?php echo $URL ?>");
    </script>
<?php
} else {
    echo "게시글 등록에 실패하였습니다.";
}

mysqli_close($connect);
?>

 

 

[write.php 개선 결과]

이전보다 UI가 간단해졌으며, 세션 관리를 통해 회원 및 게시글을 관리하기 때문에 훨씬 효율적이다.


다음은 read.php를 수정해주었다.

페이지 하단에 목록 버튼과 함께 나타나는 수정, 삭제 버튼은 게시글 작성자는 물론이고 기타 회원, 비회원에게도 나타나게 구현되었다.

이는 일반적이지 못한 UI이므로 if 조건문을 사용하여 게시글 작성자에게만 나타나도록 개선했다.

또한 로그인 및 로그아웃 버튼을 상단에 추가했다.

 

드디어 query문을 추가하여 조회수 기능을 구현했다.

index.php에서 게시글을 클릭하여 접속해보니, read.php?number=$number 내 조회수 값이 곧바로 +1 되지 않는 것을 확인했다.

그래서 DB의 조회수 속성값에 +1을 추가하여 출력하도록 구현했다.

(개선 소스코드 참고)

 

 

[read.php 개선 소스코드]

<!DOCTYPE html>
<html>

<head>
    <meta charset='utf-8'>

    <style>
        .read_table {
            border: 1px solid #444444;
            margin-top: 30px;
        }

        .read_title {
            height: 45px;
            font-size: 23.5px;
            text-align: center;
            background-color: #3C3C3C;
            color: white;
            width: 1000px;
        }

        .read_id {
            text-align: center;
            background-color: #EEEEEE;
            width: 30px;
            height: 33px;
        }

        .read_id2 {
            background-color: white;
            width: 60px;
            height: 33px;
            padding-left: 10px;
        }

        .read_hit {
            background-color: #EEEEEE;
            width: 30px;
            text-align: center;
            height: 33px;
        }

        .read_hit2 {
            background-color: white;
            width: 60px;
            height: 33px;
            padding-left: 10px;
        }

        .read_content {
            padding: 20px;
            border-top: 1px solid #444444;
            height: 500px;
        }

        .read_btn {
            width: 700px;
            height: 200px;
            text-align: center;
            margin: auto;
            margin-top: 40px;
        }

        .read_btn1 {
            height: 45px;
            width: 90px;
            font-size: 20px;
            text-align: center;
            background-color: #3C3C3C;
            border: 2px solid black;
            color: white;
            border-radius: 10px;
        }

        .read_comment_input {
            width: 700px;
            height: 500px;
            text-align: center;
            margin: auto;
        }

        .read_text3 {
            font-weight: bold;
            float: left;
            margin-left: 20px;
        }

        .read_com_id {
            width: 100px;
        }

        .read_comment {
            width: 500px;
        }
    </style>
</head>

<body>
    <?php
    $connect = mysqli_connect('127.0.0.1', 'root', 'password', 'db_board');
    $number = $_GET['number'];  // GET 방식 사용
    session_start();
    $query = "select title, content, date, hit, id from board where number = $number";
    $result = $connect->query($query);
    $rows = mysqli_fetch_assoc($result);

    $hit = "update board set hit = hit + 1 where number = $number";
    $connect->query($hit);

    if (isset($_SESSION['userid'])) {
    ?><b><?php echo $_SESSION['userid']; ?></b>님 반갑습니다.
        <button onclick="location.href='./logout_action.php'" style="float:right; font-size:15.5px;">로그아웃</button>
        <br />
    <?php
    } else {
    ?>
        <button onclick="location.href='./login.php'" style="float:right; font-size:15.5px;">로그인</button>
        <br />
    <?php
    }
    ?>

    <table class="read_table" align=center>
        <tr>
            <td colspan="4" class="read_title"><?php echo $rows['title'] ?></td>
        </tr>
        <tr>
            <td class="read_id">작성자</td>
            <td class="read_id2"><?php echo $rows['id'] ?></td>
            <td class="read_hit">조회수</td>
            <td class="read_hit2"><?php echo $rows['hit'] + 1 ?></td>
        </tr>


        <tr>
            <td colspan="4" class="read_content" valign="top">
                <?php echo $rows['content'] ?></td>
        </tr>
    </table>

    <!-- MODIFY & DELETE 추후 세션처리로 보완 예정 -->
    <div class="read_btn">
        <button class="read_btn1" onclick="location.href='./index.php'">목록</button>&nbsp;&nbsp;
        <?php
        if (isset($_SESSION['userid']) and $_SESSION['userid'] == $rows['id']) { ?>
            <button class="read_btn1" onclick="location.href='./modify.php?number=<?= $number ?>'">수정</button>&nbsp;&nbsp;
            <button class="read_btn1" onclick="location.href='./delete.php?number=<?= $number ?>&id=<?= $_SESSION['userid'] ?>'">삭제</button>
        <?php } ?>

    </div>
</body>

</html>

 

 

[read.php 개선 결과 - 게시글 작성자]

 

[read.php 개선 결과 - 기타 회원]

 

[read.php 개선 결과 - 비회원]

이제야 좀 구실을 갖춰가는 것 같아서 뿌듯하기도 하다.

 

본 게시판은 단순 학습을 위한 개발이므로 UI(사용자 인터페이스)를 크게 신경쓰지 않았지만, UI 구현시 유연성, 유효성, 학습성, 직관성을 고려하여야 한다.

 

다음 포스팅은 CRUD 중 Update와 Delete에 대해서 다뤄볼 예정이다.

끝~!~!~!~!~!~!~!~!~!~!~!~!~!~!

Comments