PHP 프로그래밍

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


Web Programming >> PHP Programming
[목차]
제19장 대화방 만들기(MySQL)

    1. 대화방 기본 기능 구현

 

1. 대화방 테이블(room) 만들기

 

CREATE TABLE room (
uid int(10) unsigned DEFAULT '1' NOT NULL auto_increment,
room varchar(30) DEFAULT '' NOT NULL,
PRIMARY KEY (uid)
)
;

 

2. 대화방 흐름도

 

 

3. 대화방 만들기

디렉토리구조는 /bbs/chat/로서, 이 디렉토리 밑에 아래의 파일을 만들면 됩니다.

또한, BBS메뉴(/bbs/menu.html)에 대화방을 연결하면 됩니다.

파일명 : /bbs/menu.html

<?

if(!$user_id || !$user_name) {

        echo "<SCRIPT>location.replace('login.html');</SCRIPT>";

        exit;

}

?>

<HTML>

<HEAD>

<TITLE> 회원만이 볼 수 있는 화면 </TITLE>

</HEAD>

 

<BODY BGCOLOR="#FFFFFF">

<UL>

        <LI> <A HREF="passwd.html" target="leelab-detail">암호변경</A>

        <LI> <A HREF="change.html" target="leelab-detail">개인정보변경</A><br>

        <LI> <A HREF="admin/member" target="leelab-detail">회원관리</A><br>

 

        <LI> <A HREF="message/" target="_blank">쪽지함</A><br>

        <LI> <A HREF="chat/room_list.html" target="_blank">대화방</A><br>

 

        <LI> <a href="logout.html" target="_top">종료</a>

</UL>

</BODY>

</HTML>

 

 

 

여기부터는 /bbs/chat/ 디렉토리 밑에 파일을 만들면 됩니다.

파일명 : room_list.html

 

 

<?

if(!$user_id || !$user_name) {

        echo "<SCRIPT>self.close();</SCRIPT>";

        exit;

}

?>

<center><h1>Lee LAB 대화방 </h1><center>

<hr width=80%>

<?

########## 데이터베이스 서버에 연결한다. ##########

$dbconn = mysql_connect("localhost","php","php99") or die("DB서버 연결에 실패하였습니다!");

 

########## 작업 데이터베이스로 sample을 선택한다. ##########

$status = mysql_select_db("sample",$dbconn);

if(!$status) {

   $errNO = mysql_errno($dbconn);

   $errMSG = mysql_error($dbconn);

 

   echo("서버의 sample 데이터베이스연결에 실패하였습니다!<br>");

   echo("에러코드 $errNO : $errMSG<br>");

   exit;

}

 

$message = "님께서 입장하였습니다.";

$result= mysql_query ("select * from room ", $dbconn);

 

$Total = mysql_num_rows($result);

 

if (!$Total){

echo ("<center><h1>아직 생성된 방이 없네요 </h1><center>");

}else{

 

echo ("

   <center>

<table width='52%' border='0' cellspacing='0' cellpadding='0'>

  <tr bgcolor='#000000'>

    <td height='26' width='90%'>

      <div align='center'><font color='#FFFFFF' size='2'>생성된 대화방 이름 </font></div>

    </td>

  </tr>

");

$counter = 0;

 

while ($counter < $Total):

$uid = mysql_result($result, $counter, "uid");

$room = mysql_result($result, $counter, "room");

 

echo ("

<tr>

    <td height='36' width='90%'><a href='room_login.html?room=$room&message=$message'>$room</td>

  </tr>

 

");

$counter = $counter +1;

 

endwhile;

}

echo("

<center>

<FORM ACTION='room_create.html' METHOD='POST'>

    <table width='37%' border='1' cellspacing='0' cellpadding='0' height='86' bordercolor='#000000'>

      <tr bgcolor='#999999'>

        <td height='29'>

          <div align='center'><font color='#FFFFFF' size='2'>◈ 대화방 ◈</font></div>

        </td>

      </tr>

      <tr>

        <td>

          <div align='center'><font size='2'>대화방제목

            <input type=text name=room size=15>

            <input type=submit value='대화방만들기' name='submit'>

            </font> </div>

        </td>

      </tr>

    </table>

    <font size='2'>대화방제에 공백이 있으면 안됩니다. </font>

  </form>

</center>

");

?>

 

파일명 : room_create.html

<?

if(!$user_id || !$user_name) {

        echo "<SCRIPT>self.close();</SCRIPT>";

        exit;

}

 

if (!$room) {

 

        echo ("

                <script>

                window.alert ('대화방제목은?')

                history.go(-1)

                </script>

        ");

        exit;

 

}

 

$message_dir = "./data"; //message 디랙토리의 절대경로

 

########## 데이터베이스 서버에 연결한다. ##########

$dbconn = mysql_connect("localhost","php","php99") or die("DB서버 연결에 실패하였습니다!");

 

########## 작업 데이터베이스로 sample을 선택한다. ##########

$status = mysql_select_db("sample",$dbconn);

if(!$status) {

   $errNO = mysql_errno($dbconn);

   $errMSG = mysql_error($dbconn);

 

   echo("서버의 sample 데이터베이스연결에 실패하였습니다!<br>");

   echo("에러코드 $errNO : $errMSG<br>");

   exit;

}

 

$result= mysql_query ("select * from room where room = '$room'", $dbconn);

$Total = mysql_num_rows($result);

if($Total) {

        echo ("

                <script>

                window.alert ('같은 대화방 제목이 있습니다.')

                history.go(-1)

                </script>

        ");

        exit;

 

}

mysql_query("insert into room (room) values('$room')", $dbconn);

 

             

if($tomsg == "") {

        $tomsg = all;

}

 

$newmessage = "$tomsg|$user_name|<font size=-1 color=$ucolor><B>$user_name</B>님께서 대화방을 만들었습니다.</font><br>";

$fp=fopen ("$message_dir/${room}.html", "w");

fwrite($fp, "$newmessage\n");

fclose($fp);

 

echo ("

                <script>

                location.replace('room_login.html?room=$room');

                </script>

");

?>

 

 

파일명 : room_login.html

<?

echo ("

<frameset rows='*,145' frameborder='NO' border='0' framespacing='0'>

  <frame name='msg_list' src='say.html?room=$room&message=$message'>

  <frame name='msg_input' scrolling='NO' noresize src='chat.html?room=$room&message=$message'>

</frameset>

<noframes><body bgcolor='#FFFFFF'>

");

 

?>

 

파일명 : say.html

<?

//message 디랙토리의 절대경로

$message_dir = "./data";

 

$lines = file("${message_dir}/${room}.html");

header("Content-type: text/html");

print "<HTML><HEAD><META HTTP-EQUIV='Refresh' CONTENT='5; url=$PHP_SELF?room=$room'></HEAD><BODY BGCOLOR='FFFFFF'>";

for($i=0; $i<=20;$i++) {

$talk = $lines[$i];

$lsat = split('\|', $talk);

if(($lsat[0] == "") || ($lsat[0] == "all")){print "$lsat[2]";}

else{

if($lsat[0] == $user_name){print "☎귓속말:$lsat[2]";}

elseif($lsat[1] == $user_name){print "☏귓속말:$lsat[2]";}

  }

}

 

exit;

 

?>

 

파일명 : chat.html

<?

if(!$user_id || !$user_name) {

        echo "<SCRIPT>self.close();</SCRIPT>";

        exit;

}

 

//message 디랙토리 절대경로

$message_dir = "./data";

 

//대화방 퇴장시 연결될 페이지 URL

$redirect_url = "./room_list.html";

          

// 서브루틴

 

function error() {

        header("Content-type: text/html");

        return print"<body bgcolor=ffffff><h1>에러임돠 열심히 해보세요</body></html>";

exit;

}

 

function write($username, $ucolor, $room, $message, $tomsg, $ear,$message_dir){

        $lines = file("${message_dir}/${room}.html");

             

        if($tomsg == "") {

                $tomsg = all;

        }

        $newmessage = "$tomsg|$username|<font size=-1 color=$ucolor><B>$username:</B>$message</font><br>";

        $fp=fopen ("${message_dir}/${room}.html", "w");

    fwrite($fp, "$newmessage\n");

        for ($i = 0; $i < 20; $i++)  {

        fwrite($fp, "$lines[$i]");

        }

    fclose($fp);

 

}

//

if($room == "") {

      error;

}

 

// 글자색 지정

 

$ucolor=$ucolor;

if($ucolor == "") {

    $uc1 = "checked";

}

if($ucolor == "blue") {

   $uc1 = "checked";

}

if ($ucolor == "brown") {

   $uc2 = "checked";

}

if ($ucolor == "black") {

     $uc3 = "checked";

}

if ($ucolor == "green") {

     $uc4 = "checked";

}

if ($ucolor == "magenta") {

   $uc5 = "checked";

}

if ($ucolor == "RED") {

   $uc6 = "checked";

}

 

// LOG OUT

if ($logoff == "ok") {

    $date = date( "l dS of F Y h:i:s A" );

    $message = "$message($date)";

    write($user_name, $ucolor, $room, $message, $tomsg, $ear,$message_dir);

    print "<META HTTP-EQUIV=Refresh CONTENT='0; url=$redirect_url'>";

    exit;

}

 

header("Content-type: text/html");

print"

        <HTML>

 <HEAD>

   <TITLE>대화방</TITLE>

   <style>

    a:link, a:visited, a:active { text-decoration:none; color:#003366; }

    A:hover{color:blue;}

    body, tr, td { font-size : 10pt;}

   </style>

 

 <SCRIPT LANGUAGE='JavaScript'>

 <!--

 function FocusOn() {

 document.form_submit.message.focus();

 return;

 }

 

function Add(str)

{

        document.form_submit.message.focus();

        document.form_submit.message.value+=str;

        return ;

}

 

function chat()

{

  form_submit.submit();

 

}

 

 

 //-->

 </SCRIPT>

 

 </HEAD>

 

  <BODY bgcolor=#FFFFFF text=#000000 topmargin=5 onLoad=FocusOn()>

     <table  cellspacing=0 cellpadding=1 border=0>

      <tr>

       <td valign=top>

 

        <table cellspacing=0 cellpadding=3 border=0>

         <tr>

          <td> 글자색선택 : </td>

        <form name='form_submit' action='chat.html' method='post'>

          <td>

           <input type=radio name=ucolor value=#003366 checked><font color=#003366>♥</font>

           <input type=radio name=ucolor value=brown ><font color=brown>♥</font>

           <input type=radio name=ucolor value=black ><font color=black>♥</font>

           <input type=radio name=ucolor value=green ><font color=green>♥</font>

           <input type=radio name=ucolor value=magenta ><font color=magenta>♥</font>

           <input type=radio name=ucolor value=red ><font color=red>♥</font>

           <input type=radio name=ucolor value=#ff9900 ><font color=#ff9900>♥</font>

           <input type=radio name=ucolor value=blue ><font color=blue>♥</font>

           <input type=radio name=ucolor value=gold ><font color=gold>♥</font>

          </td>

         </tr>

         <tr>

          <td>특 수 문 자 :</td>

          <td>

                          <a href=\"javascript:Add('■')\">■</a>

                          <a href=\"javascript:Add('▣')\">▣</a>

                          <a href=\"javascript:Add('□')\">□</a>

                          <a href=\"javascript:Add('●')\">●</a>

                          <a href=\"javascript:Add('◎')\">◎</a>

                          <a href=\"javascript:Add('○')\">○</a>

                          <a href=\"javascript:Add('◆')\">◆</a>

                          <a href=\"javascript:Add('◈')\">◈</a>

                          <a href=\"javascript:Add('◇')\">◇</a>

                          <a href=\"javascript:Add('♥')\">♥</a>

                          <a href=\"javascript:Add('♡')\">♡</a>

                          <a href=\"javascript:Add('♠')\">♠</a>

                          <a href=\"javascript:Add('♤')\">♤</a>

                          <a href=\"javascript:Add('♣')\">♣</a>

                          <a href=\"javascript:Add('♧')\">♧</a>

                          <a href=\"javascript:Add('※')\">※</a>

                          <a href=\"javascript:Add('☞')\">☞</a>

                          <a href=\"javascript:Add('☜')\">☜</a>

                          <a href=\"javascript:Add('★')\">★</a>

<br>

                          <a href=\"javascript:Add('☆')\">☆</a>

                          <a href=\"javascript:Add('◑')\">◑</a>

                          <a href=\"javascript:Add('◐')\">◐</a>

                          <a href=\"javascript:Add('◀')\">◀</a>

                          <a href=\"javascript:Add('◁')\">◁</a>

                          <a href=\"javascript:Add('▶')\">▶</a>

                          <a href=\"javascript:Add('▷')\">▷</a>

                          <a href=\"javascript:Add('☏')\">☏</a>

                          <a href=\"javascript:Add('☎')\">☎</a>

                          <a href=\"javascript:Add('♨')\">♨</a>

                          <a href=\"javascript:Add('♪')\">♪</a>

                          <a href=\"javascript:Add('♩')\">♩</a>

                          <a href=\"javascript:Add('♀')\">♀</a>

                          <a href=\"javascript:Add('♂')\">♂</a>

                          <a href=\"javascript:Add('∴')\">∴</a>

                          <a href=\"javascript:Add('▼')\">▼</a>

                          <a href=\"javascript:Add('▽')\">▽</a>

                          <a href=\"javascript:Add('▲')\">▲</a>

                          <a href=\"javascript:Add('△')\">△</a>

          </td>

         </tr>

         <tr>

          <td> 대 화 입 력 : </td>

          <td>

           <input name=room type=hidden value='$room'>

           <input type=text name=message value='' size=45>

&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:form1.submit()'>Logout</a>

 

          </td>

       </form>

      <form name= form1 action='chat.html' method='post' target=_top>

        <input name=room type=hidden value='$room'>

        <input name='logoff' type=hidden value='ok'>

        <input type=hidden name=message value='님이 퇴장하셨습니다!'>

      </form>

 

        </tr>

       </TABLE>

 

     </td>

    </tr>

   </table>

 

        ";

 

        if($ear == "귓속말") {

                $tom = split(';',$message);

                $tomsg = $tom[0];

        $msg = $tomsg[1];

                if(($tomsg) && ($msg)) {

                        $message = $msg;

 

                }

        }

        if ($message) { 

                write($user_name, $ucolor, $room, $message, $tomsg, $ear,$message_dir); 

                echo(" <SCRIPT LANGUAGE='JavaScript'>

                 <!--

                  top.msg_list.document.location.href='say.html?room=$room&message=$message'

                 //-->

                 </SCRIPT>");

 

        }               

        exit;

?>

[목차]

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

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

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