[시스템분석설계] 중간고사 정리

Useful·2025년 4월 21일
0

대학_정리

목록 보기
3/3

[2주차] 웹시스템실습 1 (DB 연동)


팀별과제1 : 웹시스템실습(DB 연동)

  • 간단한 회원관리 테이블을 만들고(제시된 테이블을 사용한다면 1개 이상의 필드를 필히 수정할 것!)
  • 회원 가입 웹 페이지 완성하기(강의자료에 참고자료 있음)

학습 절차

  1. 테스트 DB를 만든다.
  2. 그 DB에 간단한 회원관리 테이블을 만든다
  3. 회원관리를 위한 폼 페이지를 만든다.
  4. 회원관리를 위한 액션 페이지를 만든다.
  5. 브라우저에서 실행해 보며 전체 소스를 파악한다

참고 자료

1. 폼 페이지 : member_form.php

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<title>PHP 프로그래밍 입문</title>
<link rel="stylesheet" type="text/css" href="./css/common.css">
<link rel="stylesheet" type="text/css" href="./css/member.css">
<script>
   function check_input()
   {
      if (!document.member_form.id.value) {
          alert("아이디를 입력하세요!");    
          document.member_form.id.focus();
          return;
      }

      if (!document.member_form.pass.value) {
          alert("비밀번호를 입력하세요!");    
          document.member_form.pass.focus();
          return;
      }

      if (!document.member_form.pass_confirm.value) {
          alert("비밀번호확인을 입력하세요!");    
          document.member_form.pass_confirm.focus();
          return;
      }

      if (!document.member_form.name.value) {
          alert("이름을 입력하세요!");    
          document.member_form.name.focus();
          return;
      }

      if (!document.member_form.email1.value) {
          alert("이메일 주소를 입력하세요!");    
          document.member_form.email1.focus();
          return;
      }

      if (!document.member_form.email2.value) {
          alert("이메일 주소를 입력하세요!");    
          document.member_form.email2.focus();
          return;
      }

      if (document.member_form.pass.value != 
            document.member_form.pass_confirm.value) {
          alert("비밀번호가 일치하지 않습니다.\n다시 입력해 주세요!");
          document.member_form.pass.focus();
          document.member_form.pass.select();
          return;
      }

      document.member_form.submit();
   }

   function reset_form() {
      document.member_form.id.value = "";  
      document.member_form.pass.value = "";
      document.member_form.pass_confirm.value = "";
      document.member_form.name.value = "";
      document.member_form.email1.value = "";
      document.member_form.email2.value = "";
      document.member_form.id.focus();
      return;
   }

   function check_id() {
     window.open("member_check_id.php?id=" + document.member_form.id.value,
         "IDcheck",
          "left=700,top=300,width=350,height=200,scrollbars=no,resizable=yes");
   }
</script>
</head>
<body> 
	<header>
    	<?php include "header.php";?>
    </header>
	<section>
		<div id="main_img_bar">
            <img src="./img/main_img.png">
        </div>
        <div id="main_content">
      		<div id="join_box">
          	<form  name="member_form" method="post" action="member_insert.php">
			    <h2>회원 가입</h2>
    		    	<div class="form id">
				        <div class="col1">아이디</div>
				        <div class="col2">
							<input type="text" name="id">
				        </div>  
				        <div class="col3">
				        	<a href="#"><img src="./img/check_id.gif" 
				        		onclick="check_id()"></a>
				        </div>                 
			       	</div>
			       	<div class="clear"></div>

			       	<div class="form">
				        <div class="col1">비밀번호</div>
				        <div class="col2">
							<input type="password" name="pass">
				        </div>                 
			       	</div>
			       	<div class="clear"></div>
			       	<div class="form">
				        <div class="col1">비밀번호 확인</div>
				        <div class="col2">
							<input type="password" name="pass_confirm">
				        </div>                 
			       	</div>
			       	<div class="clear"></div>
			       	<div class="form">
				        <div class="col1">이름</div>
				        <div class="col2">
							<input type="text" name="name">
				        </div>                 
			       	</div>
			       	<div class="clear"></div>
			       	<div class="form email">
				        <div class="col1">이메일</div>
				        <div class="col2">
							<input type="text" name="email1">@<input type="text" name="email2">
				        </div>                 
			       	</div>
			       	<div class="clear"></div>
			       	<div class="bottom_line"> </div>
			       	<div class="buttons">
	                	<img style="cursor:pointer" src="./img/button_save.gif" onclick="check_input()">&nbsp;
                  		<img id="reset_button" style="cursor:pointer" src="./img/button_reset.gif"
                  			onclick="reset_form()">
	           		</div>
           	</form>
        	</div> <!-- join_box -->
        </div> <!-- main_content -->
	</section> 
	<footer>
    	<?php include "footer.php";?>
    </footer>
</body>
</html>

2. 액션 페이지 : member_insert.php

<?php
    $id   = $_POST["id"];
    $pass = $_POST["pass"];
    $name = $_POST["name"];
    $email1  = $_POST["email1"];
    $email2  = $_POST["email2"];

    $email = $email1."@".$email2;
    $regist_day = date("Y-m-d (H:i)");  // 현재의 '년-월-일-시-분'을 저장

              
    $con = mysqli_connect("localhost", "user1", "12345", "sample");

	$sql = "insert into members(id, pass, name, email, regist_day, level, point) ";
	$sql .= "values('$id', '$pass', '$name', '$email', '$regist_day', 9, 0)";

	mysqli_query($con, $sql);  // $sql 에 저장된 명령 실행
    mysqli_close($con);     

    echo "
	      <script>
	          location.href = 'index.php';
	      </script>
	  ";
?>

작성한 코드

join.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="././css/style.css">
</head>
<body>
    <div class="wrap">
        <div class="header">
            <h2>회원가입</h2>
            
        </div>

        <div class="section">
            <form name="member_form" method="post" action="member_join.php">

               <ul>
                    <li><input type="text" id="user_name" name="name" placeholder="이름" > </li>
                    <li><input type="text" id="user_id" name="id" placeholder="아이디" >
                    <li><input type="password" id="user_password" name="password"  placeholder="비밀번호" ></li>
                    <li><input type="text" name="email1" placeholder="이메일" class="email1">@<input type="text" name="email2" class="email2"></li>
                    <li><input type="text" name="address" placeholder="주소"></li>
                    <li><input type="date" name="birth" value="2002-01-01" ></li>
               </ul>

               <button type="submit" class="submit_button">가입하기</button>

            </form>
        </div>

        <div class="footer"></div>
    </div>

    
</body>

<script>
    function check_input()
    {
       if (!document.member_form.id.value) {
           alert("아이디를 입력하세요!");    
           document.member_form.id.focus();
           return;
       }
 
       if (!document.member_form.pass.value) {
           alert("비밀번호를 입력하세요!");    
           document.member_form.pass.focus();
           return;
       }
 
       if (!document.member_form.pass_confirm.value) {
           alert("비밀번호확인을 입력하세요!");    
           document.member_form.pass_confirm.focus();
           return;
       }
 
       if (!document.member_form.name.value) {
           alert("이름을 입력하세요!");    
           document.member_form.name.focus();
           return;
       }
 
       if (!document.member_form.email1.value) {
           alert("이메일 주소를 입력하세요!");    
           document.member_form.email1.focus();
           return;
       }
 
       if (!document.member_form.email2.value) {
           alert("이메일 주소를 입력하세요!");    
           document.member_form.email2.focus();
           return;
       }
 
       if (document.member_form.pass.value != 
             document.member_form.pass_confirm.value) {
           alert("비밀번호가 일치하지 않습니다.\n다시 입력해 주세요!");
           document.member_form.pass.focus();
           document.member_form.pass.select();
           return;
       }
 
       document.member_form.submit();
    }
 
    function reset_form() {
       document.member_form.id.value = "";  
       document.member_form.pass.value = "";
       document.member_form.pass_confirm.value = "";
       document.member_form.name.value = "";
       document.member_form.email1.value = "";
       document.member_form.email2.value = "";
       document.member_form.id.focus();
       return;
    }
 </script>
</html>

member_join.php

<?php
    $id = $_POST["id"];
    $password = $_POST["password"];
    $name = $_POST["name"];
    $birth = $_POST["birth"];
    $address = $_POST["address"];
    $email1 = $_POST["email1"];
    $email2 = $_POST["email2"];
    
    $email = $email1."@".$email2;
    
    date_default_timezone_set("Asia/Seoul");
    $createDt = date("Y-m-d H:i:s");
    
    $con = mysqli_connect("localhost", "root", "", "testdb");
    
    $query = "insert into member(id, password, name, birth, address, email, createDt)";
    $query .= "values('$id', '$password', '$name', '$birth', '$address', '$email', '$createDt')";
    
    mysqli_query($con, "set names utf8");
    $result = mysqli_query($con, $query);
    mysqli_close($con);
    
    if($result === false) {
        echo "
            <script>
                alert('가입에 실패했습니다.');
                location.href = 'join.php';
            </script>
    ";
    } else {
        echo "
            <script>
                alert('정상적으로 가입 되었습니다');
                location.href = 'join.php';
            </script>
        ";
    }
?>

결과 사진



[3주차] 웹시스템실습 2 (로그인 처리)


팀별과제2

  • 로그인 완성하기(로그인 성공하면 “로그인 성공!!”을 띄우고 실패하면 다시 로그인 하게)
  • 보안 강화를 위해 로그인 실패 시 총 3회만 재시도 기회를 부여하게 하고 4회부터는 회원가입
    페이지로 이동하게 하기( session 이용할 것! )

학습 절차

  1. 지난 주 완성한 페이지 첫 화면에 ‘회원가입’ 외에 ‘로그인’을 할 수 있게 추가한다.
  2. 로그인을 처리할 액션페이지를 만든다.
  3. 브라우저에서 실행해 보며 전체 소스를 파악한다

작성한 코드

로그인 폼 : login.php

<?php
    // 세션 시작
    session_start();
    
    // 로그인 실패 횟수를 저장하는 세션 변수 'count'가 없으면 -> 세션 변수 count를 생성
    if(!isset($_SESSION['count'])) {
        $_SESSION['count'] = 0;
    }
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="././css/login.css">
        <title>Document</title>
        
        <script>
        	// 회원가입 페이지로 이동하는 JS 코드
        	function joinPage() {
        		location.href = 'join.php';
        	}
        </script>
    </head>
    <body>
        <div class="loginbox">
        <h2>Login</h2>
            <form method="post" action="member_login.php" id="login-form">
                <input type="text" name="id" placeholder="ID">
                <input type="password" name="password" placeholder="Password">
                <label for="remember-check">
                <input type="checkbox" id="remember-check">아이디 저장하기
                </label>
                <input type="submit" value="Login">
                <a id="join" onclick="joinPage()">회원가입이 필요하신가요?</a>
            </form>
        </div>
    </body>
</html>

로그인 액션페이지 : member_login.php

<?php
session_start();    // 세션 시작

$id = $_POST["id"]; // login 폼으로 부터 받아온 아이디
$password = $_POST["password"];  // login 폼으로 부터 받아온 비밀번호

$con = mysqli_connect("localhost", "root", "", "testdb");

$query = "select id, password from member where id= '".$id."'";
$result = mysqli_query($con, $query);

$record_count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

if ($record_count > 0) {
    $pass_id = $row["id"];
    $pass_pw = $row["password"];
    
    // 비밀번호 확인
    if ($pass_id === $id && $pass_pw === $password) {
        $_SESSION['count'] = 0;  // 로그인 성공 시 카운트 초기화
        echo "
            <script>
                alert('로그인 성공!!');
                location.href = 'login.php';
            </script>
        ";
    } else {
        $_SESSION['count']++;   // 로그인 실패 시 실패횟수 count 1 증가
        
        // 실패 횟수를 alert 으로 알려줌
        echo "
            <script>
                alert('로그인에 실패했습니다. 실패 횟수: " . $_SESSION['count'] . "회');
                location.href = 'login.php';
            </script>
        ";
        
        // 3회 이상 실패하고 4회째는 회원가입 페이지로 이동
        if ($_SESSION['count'] > 3) {
            $_SESSION['count'] = 0;  // 실패 후 카운트 초기화
            header("Location: join.php");
            exit();  // 회원가입 페이지로 리다이렉트 후 종료
        }
    }
} else {
    // 이 곳은 데이터베이스에 아이디가 없으면 이쪽으로 빠짐
    $_SESSION['count']++; // 실패 횟수를 1씩 증가
    
    // 로그인 실패 횟수를 알려줌
    echo "
        <script>
            alert('아이디가 없습니다! 실패 횟수: " . $_SESSION['count'] . "회');
            location.href = 'login.php';
        </script>
    ";
}

mysqli_close($con);
?>


[4주차] 웹시스템실습 3(로그인/로그아웃 및 글쓰기)


팀별과제3

  • 지난 주의 로그인 기능 보안 강화하기(보안을 위해 ID 존재 여부를 먼저 검색한 후 비밀번호가 맞는지 비교하는 방식 취하고, 로그인 실패 시 ID 존재여부를 모르게 할 것!)
  • 로그인 성공했을 때 자신의 프로필글을 쓸 수(수정할 수) 있게 하시오.(단, 로그인을 통해서만 접근 가능하게 보안 강화할 것! 직접 URL 입력으로는 못 들어오게)
  • 로그아웃 기능을 넣을 것!

학습 절차

  1. 프로필글 쓸 수 있게 DB에 필드 추가하고, 글 쓸 수 있게 페이지 만들기
  2. 로그인 기능 보안 강화하기
  3. 인증 받은 경로로만 접근 가능하게 하기
  4. 로그아웃 기능 추가하기

작성한 코드

로그인 액션페이지 : member_login.php

<?php
session_start();    // 세션 시작

$id = $_POST["id"]; // login 폼으로 부터 받아온 아이디
$password = $_POST["password"];  // login 폼으로 부터 받아온 비밀번호

$con = mysqli_connect("localhost", "root", "", "testdb");

$query = "select id, password from member where id= '".$id."'";
$result = mysqli_query($con, $query);

$record_count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

// id 존재여부 검색
if ($record_count > 0) {
    $pass_id = $row["id"];
    $pass_pw = $row["password"];
    
    // 로그인 성공 시,
    if ($pass_id === $id && $pass_pw === $password) {
        $_SESSION['count'] = 0;  // 로그인 성공 시 카운트 초기화
        
        $_SESSION['login_id'] = $pass_id;   // 세션에 id 저장
        
        // GET 방식으로 id를 profile.php 로 넘겨서 페이지 이동
        echo "
            <script>
                alert('로그인 성공!!');
                location.href = 'profile.php?id=".$id."'
            </script>
        ";
    } else {
        $_SESSION['count']++;   // 로그인 실패 시 실패횟수 count 1 증가
        
        // 실패 횟수를 alert 으로 알려줌
        echo "
            <script>
                alert('로그인에 실패했습니다. 실패 횟수: (" . $_SESSION['count'] . "/3)');
                location.href = 'login.php';
            </script>
        ";
        
        // 3회 이상 실패하고 4회째는 회원가입 페이지로 이동
        if ($_SESSION['count'] > 3) {
            $_SESSION['count'] = 0;  // 실패 후 카운트 초기화

            header("Location: join.php");
            exit();  // 회원가입 페이지로 리다이렉트 후 종료
        }
    }
} else {
    // 이 곳은 데이터베이스에 아이디가 없으면 이쪽으로 빠짐
    $_SESSION['count']++; // 실패 횟수를 1씩 증가
    
    // 로그인 실패 횟수를 알려줌
    echo "
        <script>
            alert('로그인에 실패했습니다. 실패 횟수: (" . $_SESSION['count'] . "/3)');
            location.href = 'login.php';
        </script>
    ";
}

mysqli_close($con);
?>

프로필 폼 페이지 : profile.php

<?php
    session_start();  // 세션 시작
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>
    <link rel="stylesheet" href="./css/profile-style.css">
</head>
<body>
	<div class="wrap">
        <header>
            <ul class="gnb">
                <li><a href="logout.php">로그아웃</a></li>
            </ul>
        </header>
        
        <?php
        if(!isset($_SESSION['login_id'])) {
        ?>
        	<h1>올바르지 않은 접근입니다. 로그인을 해주세요</h1>
        <?php
        }
        else {
            $con = mysqli_connect("localhost", "root", "", "testdb");
            mysqli_set_charset($con, "utf8");
            $query = "select id, name, profileText from member where id='".$_GET["id"]."'";
            
            $result = mysqli_query($con, $query);
            $record_count = mysqli_num_rows($result);
            $row = mysqli_fetch_array($result);
            
            // 데이터가 있으면?
            if ($record_count > 0) {
                $id = $row["id"];
                $name = $row["name"];
                $profileText = $row["profileText"];
                
                echo "
                    <script>console.log('".$name."')</script>
                ";
            } else { 
                $name = "이름 없음";
                $profileText="";
            }
            
        ?> 
           <section>
                <div class="picture_frame">
                    <img src="./images/profile-img.jfif" class='profile_pic'/>
                </div>
                
                <form id="article" method="post" action="member_profile.php">
                    <div>
                        <input type="hidden" name="user_id" value=<?=$id?>></input>
                        
                        <div class=user_name">
                        	<input type="text" name="user_name" value=<?=$name?> readonly></input>
                        </div>
                        
                        <br/>
                        
                        <div class="text_frame">
                        	<span class="introdution"> 소개글</span>
                        	<textarea id="text-area" name="user_profile_text" cols="30" rows="5"><?=$profileText?></textarea><br/>
                        </div>
                        <input type="submit" value="저장"/>
                    </div>
                </form>
            </section>
        <?php 
        }
        ?>
	</div>
</body>
</html>

프로필 액션 페이지: member_profile.php

<?php
    $profileText = $_POST["user_profile_text"];
    $user_id = $_POST["user_id"];
    
    $con = mysqli_connect("localhost", "root", "", "testdb");
    $query = "update member set profileText = '".$profileText."' where id='".$user_id."'";
    
    mysqli_query($con, "set names utf8");
    $result = mysqli_query($con, $query);
    mysqli_close($con);
    
    if($result === true) {
        echo "
                <script>
                    alert('성공적으로 저장 되었습니다.');
                    location.href = 'profile.php?id=".$user_id."';
                </script>
        ";
    } else {
        echo "
                <script>
                    alert('저장에 실패했습니다!');
                    location.href = 'profile.php?id=".$user_id."';
                </script>
            ";
    }
?>

로그아웃 처리 페이지 : logout.php

<?php
    session_start();
    
    unset($_SESSION['login_id']);
    
    session_destroy(); // 모든 세션 삭제
    
    echo "
        <script>
            alert('로그아웃 되었습니다');
            location.href='login.php';
        </script>
    ";
?>

결과 사진



[5주차] 웹시스템실습 4 (회원관리 완성하기)


팀 과제4

  • 각자가 만든 소스를 합쳐 팀이 만든 회원관리 시스템을 완성한다.
  • 다음의 기능을 반드시 포함한다.
  • 회원가입 시 id 중복 체크 기능
  • 로그인 보안 기능
  • 로그인한 회원만 접근 가능하게 구분 기능
  • 자신의 회원정보 수정 기능
  • 회원 탈퇴 기능
  • 관리자 페이지를 만들어 회원가입 상황을 볼 수 있게 한다.
  • 전체적으로 웹서핑을 할 수 있게 매 페이지마다 자연스럽게 이동할 수 있게 할 것!(길을 잃지 않게 전체적인 흐름도를 구상할 것)
  • 필요 없는 파일과 중복파일을 정리하고 파일이름을 잘 쓸 것!

팀별 학습 절차(팀원이 의견을 나누며 함께 할 것):

  1. 웹사이트의 전체적인 흐름도를 구상하여 그려본다.
  2. DB를 점검한다. 필요한 경우 필드를 추가한다.
  3. 제시된 기능을 구현한다. 이 때 파일이름을 일관성 있게 정의한다.
  4. 브라우저에서 실행해 보며 전체 소스를 파악한다

작성한 코드

회원가입 폼 페이지 : join.php

<?php
    session_start();
    
    // id 중복체크를 했는지 검사하는 부분
    if(!isset($_SESSION["is_checked"])) {
        $_SESSION['is_checked'] = false;
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="././css/style.css">
    <script>
    	   function check_id() {
     		window.open("id_check.php?id=" + document.member_form.id.value,
         	"ID 중복 확인",
          	"left=700,top=300,width=350,height=200,scrollbars=no,resizable=yes");
   			}
    </script>
</head>
<body>
    <div class="wrap">
        <div class="header">
            <h2>회원가입</h2>
            
        </div>

        <div class="section">
            <form name="member_form" method="post" action="member_join.php">

               <ul>
                    <li><input type="text" id="user_name" name="name" placeholder="이름" > </li>
                    <li>
                    	<input type="text" id="user_id" name="id" placeholder="아이디" class="email1">
                    	<input type="button" id="id_duplicate" value="id 중복 확인" class="email2" onclick="check_id()">
                    </li>
                    <li><input type="password" id="user_password" name="password"  placeholder="비밀번호" ></li>
                    <li><input type="text" name="email1" placeholder="이메일" class="email1">@<input type="text" name="email2" class="email2"></li>
                    <li><input type="text" name="address" placeholder="주소"></li>
                    <li><input type="date" name="birth" value="2002-01-01" ></li>
               </ul>

               <button type="submit" class="submit_button">가입하기</button>

            </form>
        </div>

        <div class="footer"></div>
    </div>

    
</body>

<script>
    function check_input()
    {
       if (!document.member_form.id.value) {
           alert("아이디를 입력하세요!");    
           document.member_form.id.focus();
           return;
       }
 
       if (!document.member_form.pass.value) {
           alert("비밀번호를 입력하세요!");    
           document.member_form.pass.focus();
           return;
       }
 
       if (!document.member_form.pass_confirm.value) {
           alert("비밀번호확인을 입력하세요!");    
           document.member_form.pass_confirm.focus();
           return;
       }
 
       if (!document.member_form.name.value) {
           alert("이름을 입력하세요!");    
           document.member_form.name.focus();
           return;
       }
 
       if (!document.member_form.email1.value) {
           alert("이메일 주소를 입력하세요!");    
           document.member_form.email1.focus();
           return;
       }
 
       if (!document.member_form.email2.value) {
           alert("이메일 주소를 입력하세요!");    
           document.member_form.email2.focus();
           return;
       }
 
       if (document.member_form.pass.value != 
             document.member_form.pass_confirm.value) {
           alert("비밀번호가 일치하지 않습니다.\n다시 입력해 주세요!");
           document.member_form.pass.focus();
           document.member_form.pass.select();
           return;
       }
 
       document.member_form.submit();
    }
 
    function reset_form() {
       document.member_form.id.value = "";  
       document.member_form.pass.value = "";
       document.member_form.pass_confirm.value = "";
       document.member_form.name.value = "";
       document.member_form.email1.value = "";
       document.member_form.email2.value = "";
       document.member_form.id.focus();
       return;
    }
 </script>
</html>

아이디 체크 페이지 : id_check.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>아이디 중복 확인</title>
        
        <script>
        </script>
    </head>
    <body>
    	<h3>아이디 중복 확인</h3>
    	<?php
    	   session_start();
    	   
    	   $_SESSION['is_checked'] = true; // 중복 체크 여부 ok
    	   
    	   $id = $_GET["id"];
    	   
    	   if(!$id) {
    	       echo "<h4>아이디를 입력해주세요!</h4>";
    	   } else {
    	       $con = mysqli_connect("localhost", "root", "", "testdb");
    	       
    	       $query = "select id from member where id= '".$id."'";
    	       $result = mysqli_query($con, $query);
    	       
    	       $record_count = mysqli_num_rows($result);
    	       
    	       if($record_count) {
    	           echo "<h4>".$id."는 이미 사용중인 아이디 입니다.</h4>";
    	           echo "<h4>다른 아이디를 사용해주세요</h4>";
    	       } else {
    	           echo "<h4>".$id."는 사용 가능한 아이디 입니다.</h4>";
    	       }
    	       mysqli_close($con);
    	   }
    	?>
    </body>
</html>

회원가입 액션 페이지 : member_join.php

<?php
    if($_SESSION["is_checked"] === true) {
        $id = $_POST["id"];
        $password = $_POST["password"];
        $name = $_POST["name"];
        $birth = $_POST["birth"];
        $address = $_POST["address"];
        $email1 = $_POST["email1"];
        $email2 = $_POST["email2"];
        
        $email = $email1."@".$email2;
        
        date_default_timezone_set("Asia/Seoul");
        $createDt = date("Y-m-d H:i:s");
        
        $con = mysqli_connect("localhost", "root", "", "testdb");
        
        $query = "insert into member(id, password, name, birth, address, email, createDt)";
        $query .= "values('$id', '$password', '$name', '$birth', '$address', '$email', '$createDt')";
        
        mysqli_query($con, "set names utf8");
        $result = mysqli_query($con, $query);
        mysqli_close($con);
        
        if($result === false) {
            echo "
                    <script>
                        alert('가입에 실패했습니다.');
                        location.href = 'join.php';
                    </script>
            ";
        } else {
            echo "
                    <script>
                        alert('정상적으로 가입 되었습니다');
                        location.href = 'login.php';
                    </script>
                ";
        }
    } else {
        echo "
                <script>
                    alert('먼저 id 중복확인을 해주세요.');
                </script>
            ";
    }
?>

프로필 폼 페이지 : profile.php

<?php
    session_start();  // 세션 시작
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>
    <link rel="stylesheet" href="./css/profile-style.css">
</head>
<body>
	<div class="wrap">
	
        <?php include "header.php";?>
        
        <?php
        if(!isset($_SESSION['login_id'])) {
        ?>
        	<h1>올바르지 않은 접근입니다. 로그인을 해주세요</h1>
        <?php
        }
        else {
            $con = mysqli_connect("localhost", "root", "", "testdb");
            mysqli_set_charset($con, "utf8");
            $query = "select id, birth, address, email, password, name, profileText from member where id='".$_GET["id"]."'";
            
            $result = mysqli_query($con, $query);
            $record_count = mysqli_num_rows($result);
            $row = mysqli_fetch_array($result);
            
            // 데이터가 있으면?
            if ($record_count > 0) {
                $id = $row["id"];
                $password = $row["password"];
                $name = $row["name"];
                $birth = $row["birth"];
                $address = $row["address"];
                $email = $row["email"];
                $profileText = $row["profileText"];
                
                echo "
                    <script>console.log('".$name."')</script>
                ";
            } else { 
                $name = "이름 없음";
                $profileText="";
            }
            
        ?> 
           <section>
                <div class="picture_frame">
                    <img src="./images/profile-img.jfif" class='profile_pic'/>
                </div>
                
                <form id="article" method="post" action="member_profile.php">
                    <div>
                    	<span>아이디</span>
                        <input type="text" name="user_id" value=<?=$id?> readonly></input>
                        
                        <span>비밀번호</span>
                        <input type="text" name="user_password" value=<?=$password?>></input>
                        
                        <div class=user_name">
                        	<span>이  름</span>
                        	<input type="text" name="user_name" value=<?=$name?>></input>
                        </div>
                        
                        <span>생년월일</span>
                        <input type="date" name="user_birth" value=<?=$birth?>>
                        
                        <span>주  소</span>
                        <input type="text" name="user_address" value=<?=$address?>>
                        
                        <span>E-mail</span>
                        <input type="text" name="user_email" value=<?=$email?>>
                        
                        <div class="text_frame">
                        	<span class="introdution"> 소개글</span>
                        	<textarea id="text-area" name="user_profile_text" cols="30" rows="5"><?=$profileText?></textarea><br/>
                        </div>
                        <input type="submit" value="저장"/>
                    </div>
                </form>
                <br/><br/><br/>
                <a href="user_delete.php" id="btn_user_delete">회원 탈퇴</a>
            </section>
        <?php 
        }
        ?>
	</div>
</body>
</html>

프로필 액션 페이지 : member_profile.php

<?php
    $user_id = $_POST["user_id"];
    $user_password = $_POST["user_password"];
    $user_name = $_POST["user_name"];
    $user_birth = $_POST["user_birth"];
    $user_address = $_POST["user_address"];
    $user_email = $_POST["user_email"];
    $profileText = $_POST["user_profile_text"];
    
    $con = mysqli_connect("localhost", "root", "", "testdb");
    $query = "update member set password='".$user_password."', profileText = '".$profileText."', ";
    $query .= "name = '".$user_name."', birth='".$user_birth."', address='".$user_address."', email='".$user_email."'";
    $query .=" where id='".$user_id."'";
    
    mysqli_query($con, "set names utf8");
    $result = mysqli_query($con, $query);
    mysqli_close($con);
    
    if($result === true) {
        echo "
                <script>
                    alert('성공적으로 저장 되었습니다.');
                    location.href = 'profile.php?id=".$user_id."';
                </script>
        ";
    } else {
        echo "
                <script>
                    alert('저장에 실패했습니다!');
                    location.href = 'profile.php?id=".$user_id."';
                </script>
            ";
    }
?>

헤더 페이지 : header.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>
    <link rel="stylesheet" href="./css/profile-style.css">
</head>
<body>
        <header>
            <ul class="gnb">
            <?php
                $id = $_SESSION['login_id'];
                if($id === "admin") {
                    echo "<li><a href='admin_member.php'>관리자페이지</a></li>";
                }
            ?>
                <li><a href="logout.php">로그아웃</a></li>
            </ul>
        </header>
</body>

관리자 확인 페이지 : admin_member.php

<?php
    session_start();
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="././css/login.css">
        <title>관리자 페이지</title>
        <style>
            table, th, td {
                border: 1px solid black;
                border-collapse: collapse;
                padding: 5px;
            }
            th {
                background-color: #008b8b;
                color:white;
            }
        </style>
    </head>
    <body>
    <?php
    if(!isset($_SESSION['login_id'])) {
        echo "<h1>잘못된 접근입니다.</h1>";
    }
    if(isset($_SESSION['login_id'])) {
        $id = $_SESSION["login_id"];
        if($id != "admin") {
            echo "<h1>권한이 없습니다!</h1>";
        }
        else { // start else
    ?>
    	<h1>회원가입 상황</h1><br/>
    	<table>
    		<tr>
    			<th>아이디</th>
    			<th>비밀번호</th>
    			<th>이  름</th>
    			<th>생년월일</th>
    			<th>주  소</th>
    			<th>E-mail</th>
    			<th>등록일</th>
    			<th>소개글</th>
    		</tr>
    		<?php
        		$con = mysqli_connect("localhost", "root", "", "testdb");
        		
        		$query = "select * from member";
        		mysqli_query($con, "set names utf8");
        		$result = mysqli_query($con, $query);
        		
        		$record_count = mysqli_num_rows($result);
        		
        		while($row = mysqli_fetch_array($result)) {
        		    $id = $row["id"];
        		    $password = $row["password"];
        		    $name = $row["name"];
        		    $birth = $row["birth"];
        		    $address = $row["address"];
        		    $email = $row["email"];
        		    $createDt = $row["createDt"];
        		    $profileText = $row["profileText"];
        		    
        		    echo "<tr>";
        		    echo "<td>".$id."</td>";
        		    echo "<td>".$password."</td>";
        		    echo "<td>".$name."</td>";
        		    echo "<td>".$birth."</td>";
        		    echo "<td>".$address."</td>";
        		    echo "<td>".$email."</td>";
        		    echo "<td>".$createDt."</td>";
        		    echo "<td>".$profileText."</td>";
        		    echo "</tr>";
        		}
    		?>
    	</table>
    	<?php
        } // end else
    	?>
    <?php
    }
    ?>
    </body>
</html>

회원탈퇴 처리 페이지 : user_delete.php

<?php
    session_start();
    
    $id = $_SESSION["login_id"];
    $con = mysqli_connect("localhost", "root", "", "testdb");
    
    $query = "delete from member where id = '".$id."'";
    $result = mysqli_query($con, $query);
    mysqli_close($con);
    
    if($result === false) {
        echo "
                <script>
                    alert('탈퇴에 실패했습니다. 나중에 다시 시도해주세요.');
                    location.href = 'profile.php?id=".$id."'
                </script>
        ";
    } else {
        echo "
                <script>
                    alert('정상적으로 탈퇴 되었습니다.');
                    location.href = 'login.php';
                </script>
            ";
    }
?>

결과 사진



[6주차] 웹시스템실습 5 (게시판 만들기)


팀과제5

  • 게시판에 들어 갈 필수기능 : 글쓰기, 글 목록보기, 목록 클릭하여 글읽기
  • 글쓰기는 로그인한 회원만 할 수 있게 할 것!
  • 웹서핑 중 길을 잃지 않게 전체적인 흐름도를 구상할 것!
  • 필요 없는 파일과 중복파일을 정리하고 파일이름을 잘 쓸 것!

팀별 학습 절차(팀원이 의견을 나누며 함께 할 것)

  1. 게시판을 위해 DB에 테이블을 만든다.(좋은 게시판이 되게 설계를 잘 할 것)
  2. 웹사이트의 전체적인 흐름도를 구상하여 그려본다.
  3. 게시판 기능을 구현한다.
  4. 브라우저에서 실행해 보며 전체 소스를 파악한다

작성한 코드

로그인 액션 페이지 : member_login.php

<?php
session_start();    // 세션 시작

$id = $_POST["id"]; // login 폼으로 부터 받아온 아이디
$password = $_POST["password"];  // login 폼으로 부터 받아온 비밀번호

$con = mysqli_connect("localhost", "root", "", "testdb");

$query = "select id, password, name from member where id= '".$id."'";
$result = mysqli_query($con, $query);

$record_count = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);

// id 존재여부 검색
if ($record_count > 0) {
    $pass_id = $row["id"];
    $pass_pw = $row["password"];
    $user_name = $row["name"];

    // 로그인 성공 시,
    if ($pass_id === $id && $pass_pw === $password) {
        $_SESSION['count'] = 0;  // 로그인 성공 시 카운트 초기화
        
        $_SESSION['login_id'] = $pass_id;   // 세션에 id 저장
        $_SESSION['user_name'] = $user_name;


        
        // ⚠️ profile -> lobby로 수정했음 ⚠️
        // GET 방식으로 id를 lobby.php 로 넘겨서 페이지 이동
        echo "
            <script>
                alert('로그인 성공!!');
                location.href = 'lobby.php?id=".$id."'
            </script>
        ";
    } else {
        $_SESSION['count']++;   // 로그인 실패 시 실패횟수 count 1 증가
        
        // 실패 횟수를 alert 으로 알려줌
        echo "
            <script>
                alert('로그인에 실패했습니다. 실패 횟수: (" . $_SESSION['count'] . "/3)');
                location.href = 'login.php';
            </script>
        ";
        
        // 3회 이상 실패하고 4회째는 회원가입 페이지로 이동
        if ($_SESSION['count'] > 3) {
            $_SESSION['count'] = 0;  // 실패 후 카운트 초기화

            header("Location: join.php");
            exit();  // 회원가입 페이지로 리다이렉트 후 종료
        }
    }
} else {
    // 이 곳은 데이터베이스에 아이디가 없으면 이쪽으로 빠짐
    $_SESSION['count']++; // 실패 횟수를 1씩 증가
    
    // 로그인 실패 횟수를 알려줌
    echo "
        <script>
            alert('로그인에 실패했습니다. 실패 횟수: (" . $_SESSION['count'] . "/3)');
            location.href = 'login.php';
        </script>
    ";
}

mysqli_close($con);
?>

메인화면 폼 페이지 : lobby.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php include "header.php";?>  

    <p>메인페이지 입니다</p>
</body>
</html>

헤더 페이지 : header.php

<?php
    session_start(); // 세션 시작
    $id = $_SESSION['login_id']; // 로그인된 사용자 ID 가져오기
    
    // 로그인하지 않은 사용자는 error.php로 이동
    if (!isset($id)){
         echo "
                <script>
                    location.href='error.php';
                </script>
              ";
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile</title>

    <link rel="stylesheet" href="./css/profile-style.css">
</head>
<body>
    <header>
        <!-- 로비로 이동하는 링크 -->
        <span class="nav">
            <a href="lobby.php?id=<?php echo $id; ?>">로비</a>
        </span>

        <!-- 메뉴 목록 -->
        <ul class="gnb">
            <?php
                $id = $_SESSION['login_id']; // 다시 사용자 ID 불러오기 (중복은 생략 가능)
                
                // 관리자일 경우 관리자 페이지 링크 표시
                if($id === "admin") {
                    echo "<li><a href='admin_member.php'>관리자페이지</a></li>";
                }
            ?>
            <!-- 일반 메뉴 항목들 -->
            <li><a href="profile_modified.php?id=<?php echo $id; ?>">프로필</a></li>
            <li><a href="boardlist.php">게시판</a></li>
            <li><a href="logout.php">로그아웃</a></li>
        </ul>
    </header>
</body>
</html>

게시판 페이지 : boardlist.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./css/boardlist.css">
</head>
<body>
    <div class="wrap">
    	<?php include "header.php";?>
    
    <br/>
    
    <p>게시판</p>
    
    
    <div class="table_wrap">
    	<Table>
    	<tr>
    		<th>게시글번호</th>
    		<th>제목</th>
    		<th>작성자</th>
    		<th>작성일자</th>
    	</tr>
    		<?php
    		    $login_id = $_SESSION["login_id"];
    		    
        		$con = mysqli_connect("localhost", "root", "", "testdb");
        		
        		$query = "select num, title, author_name, createDt from board";
        		mysqli_query($con, "set names utf8");
        		$result = mysqli_query($con, $query);
        		
        		$record_count = mysqli_num_rows($result);
        		
        		while($row = mysqli_fetch_array($result)) {
        		    $num = $row["num"];
        		    $title = $row["title"];
        		    $authorName = $row["author_name"];
        		    $createDt = $row["createDt"];
        		    
        		    echo "<tr>";
        		    echo "<td>".$num."</td>";
        		    echo "<td><a href='post.php?num=".$num."'>".$title."<a/></td>";
        		    echo "<td>".$authorName."</td>";
        		    echo "<td>".$createDt."</td>";
        		    echo "</tr>";
        		}
    		?>
    </Table>
    <?php
        if(isset($_SESSION["login_id"])) {
    ?>
    	<a href="post_write.php?id=<?=$login_id?>">글쓰기</a>
    <?php 
        }
    ?>
    </div>
  
    </div>
</body>
</html>

게시글 자세히 보기 페이지 : post.php

<?php
    session_start();
    
    $num = $_GET['num'];
    
    $con = mysqli_connect("localhost", "root", "", "testdb");
    mysqli_set_charset($con, "utf8");
    $query = "select title, content, author_name, DATE_FORMAT(createDt,'%Y-%m-%d') 'createDt' from board where num=".$num;
    
    $result = mysqli_query($con, $query);
    $record_count = mysqli_num_rows($result);
    $row = mysqli_fetch_array($result);
    
    // 데이터가 있으면?
    if ($record_count > 0) {
        $title = $row["title"];
        $content = $row["content"];
        $authorName = $row["author_name"];
        $createDt = $row["createDt"];
    } else {
        echo "<h1>게시글을 찾을 수 없습니다!</h1>";
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?=$title?></title>
    <style>
        .post {
            margin-top: 30px;
            margin-left: 10px;
            margin-bottom: 30px;
        }
        
        .content {
            margin-top: 50px;
            padding-left: 10px;
            font-size: 20px;
            margin: 0 auto;
        }
        
        a {
            padding-left: 10px;
        }
    </style>
</head>
<body>
	<div class="post">
    	<h1><?=$title?></h1>
    	<span><b><?=$authorName?></b> · <?=$createDt?></span>
	</div>
	<div class="content">
		<span>
			<?=$content?>
		</span>
	</div>
	<br/><br/>
    <!--목록으로 클릭하면 boardlist.php로 이동함-->
	<a href="boardlist.php">목록으로</a>
</body>

글 작성 폼 페이지 : post_write.php

<?php
    $con = mysqli_connect("localhost", "root", "", "testdb");
    mysqli_set_charset($con, "utf8");
    $query = "select id, name from member where id='".$_GET["id"]."'";
    
    $result = mysqli_query($con, $query);
    $record_count = mysqli_num_rows($result);
    $row = mysqli_fetch_array($result);
    
    // 데이터가 있으면?
    if ($record_count > 0) {
        $id = $row["id"];
        $name = $row["name"];
    } else {
        $name = "이름 없음";
    }
?>
<!doctype html>
    <head>
        <meta charset="UTF-8">
        <title>게시판</title>
        <link rel="stylesheet" href="./css/post_write_style.css">
    </head>
	<body>
        <div id="board_write">
        <h1><a href="/">자유게시판</a></h1>
        <h4>글을 작성하는 공간입니다.</h4>
        
            <div id="write_area">
                <form action="write_ok.php" method="post">
                	
                	<input type="hidden" name="id" value=<?=$id?>>
                	<input type="hidden" name="name" value=<?=$name?>>
                	
                    <div id="in_title">
                    	<textarea name="title" id="utitle" rows="1" cols="55" placeholder="제목" maxlength="100" required></textarea>
                    </div>
                    
                    <div class="wi_line"></div>
                    <div id="in_content">
                    	<textarea name="content" id="ucontent" placeholder="내용" required></textarea>
                    </div>
                    
                    <div class="bt_se">
                    	<button type="submit">글 작성</button>
                    </div>
                </form>
            </div>
        </div>
	</body>
</html>

글 작성 액션 페이지 : write_ok.php

<?php
    $title = $_POST["title"];
    $author_id = $_POST["id"];
    $author_name = $_POST["name"];
    $content = $_POST["content"];
    
    $con = mysqli_connect("localhost", "root", "", "testdb");
    
    $query = "insert into board(title, author_id, author_name, content, createDt)";
    $query .= "values('$title', '$author_id', '$author_name', '$content', now())";
    
    mysqli_query($con, "set names utf8");
    $result = mysqli_query($con, $query);
    mysqli_close($con);
    
    if($result === false) {
        echo "
                    <script>
                        alert('글 작성에 실패했습니다.');
                    </script>
            ";
    } else {
        echo "
                    <script>
                        alert('글을 성공적으로 작성했습니다.');
                        location.href='boardlist.php';
                    </script>
                ";
    }
?>


[6주차] 웹시스템실습 5 (게시판 만들기)


팀과제6

  • 일반적인 게시판처럼 완성도 있는 게시판을 만들 것!
  • 댓글, 글삭제, 페이지별로 목록보이기 등 팀별로 적절히 알아서..(댓글과 글삭제 기능에서 정책을 잘 구상하세요)
  • 전체적인 흐름을 자연스럽게 할 것!
  • 필요 없는 파일과 중복파일을 정리하고 파일이름을 잘 쓸 것!

팀별 학습 절차 (팀원이 의견을 나누며 함께 할 것)

  1. 추가할 게시판 기능과 전체적인 흐름도를 구상하여 그린다.
  2. 게시판 DB를 재정비한다.
  3. 추가할 게시판 기능들을 팀원별로 나누어 구현한다.
  4. 팀원 각자가 전체 소스코드를 잘 이해하도록 하며, 브라우저에서 실행해 보며 전체 소스를 파악한다
profile
1 commit = 1 life

0개의 댓글