PHP 프로그래밍

본문 바로가기
사이트 내 전체검색


PHP 프로그래밍
PHP 프로그래밍

1. 게시판 실습(1)

페이지 정보

작성자 관리자 댓글 0건 조회 2,544회 작성일 21-05-21 22:39

본문

1. 게시판 실습(1)

1. 게시판의 기능


- 로그인한 회원이 게시판에 글쓰기
- 회원과 비회원의 글 목록 보기, 글 내용 보기
- 글을 쓴 회원이 글을 수정 및 삭제하기
- 글쓰기 시 파일 첨부하기
- 글을 쓴 회원에게 포인트 부여하기
- 첨부 파일 다운로드하기

 

2. 헤더 메인 메뉴 추가

 

파일명 : header.php

 

        <div id="menu_bar">
            <ul> 
                <li><a href="index.php">HOME</a></li>
                <li><a href="message_form.php">쪽지함</a></li>                               
                <li><a href="board_form.php">게시판</a></li>
            </ul>
        </div>

 

men_bar에 게시판 메뉴를 추가한다.

 

 

3. board 테이블 생성

 

create table board (
   num int not null auto_increment,
   id char(15) not null,
   name char(10) not null,
   subject char(200) not null,
   content text not null,       
   regist_day char(20) not null,
   hit int not null,
   file_name char(40),
   file_type char(40),
   file_copied char(40),
   primary key(num)
); 

테이블 필드는 회원 정보 관련 필드와 게시판 글 관련 필드로 구분한다.

그 외 조회수와 파일 첨부 관련 필드가 있다.

num, id, name, subject, content, regist_day, hit 필드는 not null로 설정되는 필수 입력 항목. 레코드 일련번호를 의미하는 num은 주 키와 auto_increment로 설정한다.
num 필드는 게시글의 고유한 일련번호로 이 필드를 이용하여 해당 레코드를 수정하거나 삭제한다.
id, name, subject, content 필드는 각각 글쓴이의 아이디, 이름, 게시글의 제목과 내용을 의미한다.

regist_day 필드는 게시글을 작성한 일시를 의미한다.
hit 필드는 글 조회 수를 세는 데 사용한다.

file_name, file_type, file_copied 필드는 게시글에 파일을 첨부하는 데 사용한다.

 

 

4. 글쓰기 폼 양식 제작

 

파일명 : board_form.php

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>게시판 > 글쓰기</title>
<link rel="stylesheet" type="text/css" href="./css/common.css">
<link rel="stylesheet" type="text/css" href="./css/board.css">
</head>
<body>
<header>
    <?php include "header.php";?>
</header> 
<section>
    <div id="board_box">
     <h3 id="board_title">
       게시판 > 글 쓰기
  </h3>
     <form  name="board_form" method="post" action="board_insert.php" enctype="multipart/form-data">
       <ul id="board_form">
    <li>
     <span class="col1">이름 : </span>
     <span class="col2"><?=$username?></span>
    </li>  
       <li>
        <span class="col1">제목 : </span>
        <span class="col2"><input name="subject" type="text"></span>
       </li>      
       <li id="text_area"> 
        <span class="col1">내용 : </span>
        <span class="col2">
         <textarea name="content"></textarea>
        </span>
       </li>
       <li>
           <span class="col1"> 첨부 파일</span>
           <span class="col2"><input type="file" name="upfile"></span>
       </li>
          </ul>
      <ul class="buttons">
    <li><button type="button" onclick="board_form.submit()">완료</button></li>
    <li><button type="button" onclick="location.href='board_list.php'">목록</button></li>
   </ul>
     </form>
 </div> <!-- board_box -->
</section>
<footer>
    <?php include "footer.php";?>
</footer>
</body>
</html> 

 

5. DB에 폼 양식 데이터 저장하기

 

파일명 : board_insert.php

 

<meta charset="utf-8">
<?php
    session_start();
    if (isset($_SESSION["userid"])) $userid = $_SESSION["userid"];
    else $userid = "";
    if (isset($_SESSION["username"])) $username = $_SESSION["username"];
    else $username = "";

    if ( !$userid )
    {
        echo("
                    <script>
                    alert('게시판 글쓰기는 로그인 후 이용해 주세요!');
                    history.go(-1)
                    </script>
        ");
                exit;
    }

    $subject = $_POST["subject"];
    $content = $_POST["content"];

 $subject = htmlspecialchars($subject, ENT_QUOTES);
 $content = htmlspecialchars($content, ENT_QUOTES);

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

 $upload_dir = './data/';

 $upfile_name  = $_FILES["upfile"]["name"];
 $upfile_tmp_name = $_FILES["upfile"]["tmp_name"];
 $upfile_type     = $_FILES["upfile"]["type"];
 $upfile_size     = $_FILES["upfile"]["size"];
 $upfile_error    = $_FILES["upfile"]["error"];

 if ($upfile_name && !$upfile_error)
 {
  $file = explode(".", $upfile_name);
  $file_name = $file[0];
  $file_ext  = $file[1];

  $new_file_name = date("Y_m_d_H_i_s");
  $new_file_name = $new_file_name;
  $copied_file_name = $new_file_name.".".$file_ext;     
  $uploaded_file = $upload_dir.$copied_file_name;

  if( $upfile_size  > 1000000 ) {
    echo("
    <script>
    alert('업로드 파일 크기가 지정된 용량(1MB)을 초과합니다!<br>파일 크기를 체크해주세요! ');
    history.go(-1)
    </script>
    ");
    exit;
  }

  if (!move_uploaded_file($upfile_tmp_name, $uploaded_file) )
  {
    echo("
     <script>
     alert('파일을 지정한 디렉토리에 복사하는데 실패했습니다.');
     history.go(-1)
     </script>
    ");
    exit;
  }
 }
 else
 {
  $upfile_name      = "";
  $upfile_type      = "";
  $copied_file_name = "";
 }
 
 $con = mysqli_connect("localhost", "user1", "12345", "sample");

 $sql = "insert into board (id, name, subject, content, regist_day, hit,  file_name, file_type, file_copied) ";
 $sql .= "values('$userid', '$username', '$subject', '$content', '$regist_day', 0, ";
 $sql .= "'$upfile_name', '$upfile_type', '$copied_file_name')";
 mysqli_query($con, $sql);  // $sql 에 저장된 명령 실행

 

 mysqli_close($con);                // DB 연결 끊기

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

 
파일첨부시 업로드할 폴더를 생성한다. 폴더명은 data로 한다.

 

업로드 파일의 name 속성을 upfile로 설정하여 업로드 파일의 정보가 배열 변수로 전달된다.
Test.zip 파일을 업로드한다면 $_FILES[“upfile”][“name”]에는 파일명인 test.zip 저장된다.
$_FILES[“upfile”][“tmp_name”]에는 파일명(test.zip) 대신 실제 서버에 저장되는 임시 파일명 저장.
$_FILES[“upfile”][“type”]에는 test.zip 파일의 형식 저장.
$_FILES[“upfile”][“size”]에는 test.zip 파일의 크기 저장.
$_FILES[“upfile”][“error”]에는 업로드시 발생하는 오류 정보 저장

 

 

6. 글 목록 보기

 

글쓰기 폼 양식에 내용을 입력한 다음 하단의 <완료> 클릭하면, 글 정보가 DB에 저장되고 글 목록 보기 페이지가 나타난다. 

 

파일명 : board_list.php

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>게시판 > 목록</title>
<link rel="stylesheet" type="text/css" href="./css/common.css">
<link rel="stylesheet" type="text/css" href="./css/board.css">
</head>
<body>
<header>
    <?php include "header.php";?>
</header> 
<section>
    <div id="board_box">
     <h3>
      게시판 > 목록보기
  </h3>
     <ul id="board_list">
    <li>
     <span class="col1">번호</span>
     <span class="col2">제목</span>
     <span class="col3">글쓴이</span>
     <span class="col4">첨부</span>
     <span class="col5">등록일</span>
     <span class="col6">조회</span>
    </li>
<?php
 if (isset($_GET["page"]))
  $page = $_GET["page"];
 else
  $page = 1;

 $con = mysqli_connect("localhost", "user1", "12345", "sample");
 $sql = "select * from board order by num desc";
 $result = mysqli_query($con, $sql);
 $total_record = mysqli_num_rows($result); // 전체 글 수

 $scale = 10;

 // 전체 페이지 수($total_page) 계산
 if ($total_record % $scale == 0)    
  $total_page = floor($total_record/$scale);     
 else
  $total_page = floor($total_record/$scale) + 1;
 
 // 표시할 페이지($page)에 따라 $start 계산 
 $start = ($page - 1) * $scale;     

 $number = $total_record - $start;

   for ($i=$start; $i<$start+$scale && $i < $total_record; $i++)
   {
      mysqli_data_seek($result, $i);
      // 가져올 레코드로 위치(포인터) 이동
      $row = mysqli_fetch_array($result);
      // 하나의 레코드 가져오기
   $num         = $row["num"];
   $id          = $row["id"];
   $name        = $row["name"];
   $subject     = $row["subject"];
      $regist_day  = $row["regist_day"];
      $hit         = $row["hit"];
      if ($row["file_name"])
       $file_image = "<img src='./img/file.gif'>";
      else
       $file_image = " ";
?>
    <li>
     <span class="col1"><?=$number?></span>
     <span class="col2"><a href="board_view.php?num=<?=$num?>&page=<?=$page?>"><?=$subject?></a></span>
     <span class="col3"><?=$name?></span>
     <span class="col4"><?=$file_image?></span>
     <span class="col5"><?=$regist_day?></span>
     <span class="col6"><?=$hit?></span>
    </li> 
<?php
       $number--;
   }
   mysqli_close($con);

?>
      </ul>
   <ul id="page_num">  
<?php
 if ($total_page>=2 && $page >= 2) 
 {
  $new_page = $page-1;
  echo "<li><a href='board_list.php?page=$new_page'>◀ 이전</a> </li>";
 }  
 else
  echo "<li>&nbsp;</li>";

    // 게시판 목록 하단에 페이지 링크 번호 출력
    for ($i=1; $i<=$total_page; $i++)
    {
  if ($page == $i)     // 현재 페이지 번호 링크 안함
  {
   echo "<li><b> $i </b></li>";
  }
  else
  {
   echo "<li><a href='board_list.php?page=$i'> $i </a><li>";
  }
    }
    if ($total_page>=2 && $page != $total_page)  
    {
  $new_page = $page+1; 
  echo "<li> <a href='board_list.php?page=$new_page'>다음 ▶</a> </li>";
 }
 else
  echo "<li>&nbsp;</li>";
?>
   </ul> <!-- page -->      
   <ul class="buttons">
    <li><button onclick="location.href='board_list.php'">목록</button></li>
    <li>
<?php
    if($userid) {
?>
     <button onclick="location.href='board_form.php'">글쓰기</button>
<?php
 } else {
?>
     <a href="javascript:alert('로그인 후 이용해 주세요!')"><button>글쓰기</button></a>
<?php
 }
?>
    </li>
   </ul>
 </div> <!-- board_box -->
</section>
<footer>
    <?php include "footer.php";?>
</footer>
</body>
</html> 

 

7. 글내용 보기

 

글 목록 보기 페이지에서 제목을 클릭하면 글 내용을 볼 수 있다.
글 내용 보기 페이지인 board_view.php로 이동할 때 레코드 일련번호인 $num과 페이지 번호인 $page가 함께 GET 방식으로 전달한다. 

파일명 : board_view.php

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>게시판 > 내용보기</title>
<link rel="stylesheet" type="text/css" href="./css/common.css">
<link rel="stylesheet" type="text/css" href="./css/board.css">
</head>
<body>
<header>
    <?php include "header.php";?>
</header> 
<section>
    <div id="board_box">
     <h3 class="title">
   게시판 > 내용보기
  </h3>
<?php
 $num  = $_GET["num"];
 $page  = $_GET["page"];

 $con = mysqli_connect("localhost", "user1", "12345", "sample");
 $sql = "select * from board where num=$num";
 $result = mysqli_query($con, $sql);

 $row = mysqli_fetch_array($result);
 $id      = $row["id"];
 $name      = $row["name"];
 $regist_day = $row["regist_day"];
 $subject    = $row["subject"];
 $content    = $row["content"];
 $file_name    = $row["file_name"];
 $file_type    = $row["file_type"];
 $file_copied  = $row["file_copied"];
 $hit          = $row["hit"];

 $content = str_replace(" ", "&nbsp;", $content);
 $content = str_replace("\n", "<br>", $content);

 $new_hit = $hit + 1;
 $sql = "update board set hit=$new_hit where num=$num";  
 mysqli_query($con, $sql);
?>  
     <ul id="view_content">
   <li>
    <span class="col1"><b>제목 :</b> <?=$subject?></span>
    <span class="col2"><?=$name?> | <?=$regist_day?></span>
   </li>
   <li>
    <?php
     if($file_name) {
      $real_name = $file_copied;
      $file_path = "./data/".$real_name;
      $file_size = filesize($file_path);

      echo "▷ 첨부파일 : $file_name ($file_size Byte) &nbsp;&nbsp;&nbsp;&nbsp;
            <a href='download.php?num=$num&real_name=$real_name&file_name=$file_name&file_type=$file_type'>[저장]</a><br><br>";
               }
    ?>
    <?=$content?>
   </li>  
     </ul>
     <ul class="buttons">
    <li><button onclick="location.href='board_list.php?page=<?=$page?>'">목록</button></li>
    <li><button onclick="location.href='board_modify_form.php?num=<?=$num?>&page=<?=$page?>'">수정</button></li>
    <li><button onclick="location.href='board_delete.php?num=<?=$num?>&page=<?=$page?>'">삭제</button></li>
    <li><button onclick="location.href='board_form.php'">글쓰기</button></li>
  </ul>
 </div> <!-- board_box -->
</section>
<footer>
    <?php include "footer.php";?>
</footer>
</body>
</html> 

 

8. 첨부 파일 다운로드

 

글 내용 보기 페이지(board_view.php)에서 첨부 파일명 옆에 있는 <저장>을 클릭하면 파일 다운로드 가능하다.
이 버튼은 다음 URL로 링크되어 있다.

board_download.php?num=$num&real_name=$real_name&file_name=$file_name&file_ type=$file_type

 

파일명 : board_download.php

 

<?php
    $real_name = $_GET["real_name"];
    $file_name = $_GET["file_name"];
    $file_type = $_GET["file_type"];
    $file_path = "./data/".$real_name;

    $ie = preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) ||
        (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0') !== false &&
            strpos($_SERVER['HTTP_USER_AGENT'], 'rv:11.0') !== false);

    //IE인경우 한글파일명이 깨지는 경우를 방지하기 위한 코드
    if( $ie ){
         $file_name = iconv('utf-8', 'euc-kr', $file_name);
    }

    if( file_exists($file_path) )
    {
  $fp = fopen($file_path,"rb");
  Header("Content-type: application/x-msdownload");
        Header("Content-Length: ".filesize($file_path));    
        Header("Content-Disposition: attachment; filename=".$file_name);  
        Header("Content-Transfer-Encoding: binary");
  Header("Content-Description: File Transfer");
        Header("Expires: 0");      
    }
 
    if(!fpassthru($fp))
  fclose($fp);
?>

   

게시판 사용자가 첨부 파일을 다운로드할 수 있게 하는 board_download.php에서는 레코드 일련번호($num), 서버 저장 파일명($real_name), 파일명($file_name), 파일 형식($file_type)을 글 내용 보기 페이지로부터 GET 방식으로 전달받는다. 

 

첨부파일

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.