티스토리 뷰

다음 코드는 로그인 기능을 구현한 코드입니다.

게시판 전체 코드는 https://github.com/dhffll/php-Mysql-Board 깃허브에서 확인하실 수 있습니다.

 

login.php

<?php 
    include 'mysql.php'; //DB 연결 $con

    if(!empty($_POST['id'])){
        $filtered=[
            'id' => mysqli_real_escape_string($con,$_POST['id']),
            'pw' => mysqli_real_escape_string($con,$_POST['pw'])
        ];
        $sql = "select password from member where id = '{$filtered['id']}'";
        $result = mysqli_query($con,$sql);
        
        $num = mysqli_num_rows($result);
        if($num==0){
            echo "<script> alert('로그인 실패'); </script>";
        }
        while($row = mysqli_fetch_array($result)){
            if($filtered['pw'] == $row['password']){
                session_start();
                $_SESSION['id'] = $filtered['id'];
                header("location: index.php");
            }else{
                echo "<script> alert('로그인 실패'); </script>";
            }
        }
    }

    include 'header.php';
?>

<h1><a href="index.php">Board</a></h1>
<form action="login.php" method="POST">
    <p><input type="id" name="id" id='id' placeholder="id" autocomplete="off" required></p>
    <p><input type="password" name="pw" id='pw' placeholder="pw" autocomplete="off" required></p>
    <p><input type="submit" id="submit" value="login"></p>
</form>

<?php 
    include 'footer.php';
?>

로그인 폼을 전송했을 때 아이디가 없거나 아이디와 비밀번호가 일치하지 않을 때 alert 처리를 해주고, 로그인 성공 시에는 index.php 파일로 이동합니다.

중요한 부분은 session_start() 메소드로 세션을 시작해주는 것입니다. 그리고 $_SESSION['id']에 아이디를 넣어주면 로그인 성공입니다.

 

 

index.php (로그인 시 권한 주기)

<?php
session_start();
include 'mysql.php';
include 'header.php';
?>

<h1><a href="index.php">Board</a></h1><br>

<?php
if (empty($_SESSION['id'])) {
?>
    <a href='login.php'>login</a>
    <a href='resister.php'>signup</a>
<?php
} else {
?>
    <span>Welcome, <?= $_SESSION['id'] ?>!</span>
    <a href='create.php'>write</a>
    <a href='logout.php'>logout</a>
    <a href="change_info.php">info</a>
<?php
}
?>

<?php
include 'footer.php';
?>

로그인 상태일 때는 글쓰기 버튼과 로그아웃, 회원정보 수정 버튼을 보여주고 Welcome, {id}를 넣어줍니다.

로그아웃 상태일 때는 로그인, 회원가입 버튼을 보여주게 됩니다.

 

logout.php

<?php
  session_start();
  session_destroy();
  header('Location: index.php');
?>

로그아웃은 우선 세션을 시작해준 뒤 session_destory() 함수를 써주면 저장해둔 세션이 종료하게 되면서 다시 index.php 파일로 이동하게 됩니다.