Cách tạo Box chat đơn giản bằng PHP

Thảo luận trong 'PHP' bắt đầu bởi white.smut, 3 Tháng mười hai 2012.

  1. Offline

    white.smut

    • Administrator

    • Loading: |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||] 99% Completed - Error: Disconnected. Please try again!
    Số bài viết:
    842
    Đã được thích:
    425
    Điểm thành tích:
    450
    Tạo Box Chat đơn giản gồm những phần cơ bản sau:

    Bước 1: Tạo biểu mẫu (index.html):
    Mã:
    <html>
    <head>
    <title>ChatBox Beta 1</title>
    <link rel="stylesheet" type="text/css" href="cb_style.css">
    <script type="text/javascript" src="ajax.js"></script>
    <script type="text/javascript" src="chatbox.js"></script>
    </head>
    <body onbeforeunload="signInForm.signInButt.name='signOut';signInOut()" onload="hideShow('hide')">
    <h1>Chat Box</h1>
    <form onsubmit="signInOut();return false" id="signInForm">
    <input id="userName" type="text">
    <input id="signInButt" name="signIn" type="submit" value="Sign in">
    <span id="signInName">User name</span>
    </form>
    <div id="chatBox"></div>
    <div id="usersOnLine"></div>
    <form onsubmit="sendMessage();return false" id="messageForm">
    <input id="message" type="text">
    <input id="send" type="submit" value="Send">
    <div id="serverRes"></div></form>
    </body>
    </html>
    Bước 2: Tạo phông cách (cb_style.css) gồm 9 thành phần:

    Mã:
    #signInForm, #messageForm {
    margin:0px;
    margin-bottom:1px;
    }
    #userName {
    width: 150px;
    height: 22px;
    border: 1px teal solid;
    float:left;
    }
    #signInButt {
    width: 60px;
    height: 22px;
    }
    #signInName{
    font-family:Tahoma;
    font-size:12px;
    colorrange;
    }
    #chatBox {
    font-family:tahoma;
    font-size:12px;
    color:black;
    border: 1px teal solid;
    height: 225px;
    width: 400px;
    overflow: scroll;
    float:left;
     
    }
    #usersOnLine{
    font-family:tahoma;
    font-size:14;
    colorrange;
    border:1px teal solid;
    width:150px;
    height:225px;
    overflow:scroll;
    margin-left:1px;
    }
    #message {
    width: 350px;
    height: 22px;
    border: 1px teal solid;
    float:left;
    margin-top:1px;
    }
    #send {
    width: 50px;
    height: 22px;
    float:left;
    margin:1px;
    }
    #serverRes{
    width:150px;
    height:22px;
    border: 1px teal solid;
    float:left;
    margin:1px;
    }
    Bước 3: Tạo file receive.php

    Mã:
    <?php
    $lastreceived=$_POST['lastreceived'];
    $room_file=file("room1.txt",FILE_IGNORE_NEW_LINES);
    for($line=0;$line<count($room_file);$line++){
    $messageArr=split("<!@!>",$room_file[$line]);
    if($messageArr[0]>$lastreceived)echo $messageArr[1]."<br>";
    }
    echo "<SRVTM>".$messageArr[0];
    ?>
    Bước 4: Tạo file send.php

    Mã:
    <?php
    $message=strip_tags($_POST['message']);
    $message=stripslashes($message);
    $user=$_POST['user'];
     
    $room_file=file("room1.txt",FILE_IGNORE_NEW_LINES);
     
    $room_file[]=time()."<!@!>".$user.": ".$message;
    if (count($room_file)>20)$room_file=array_slice($room_file,1);
    $file_save=fopen("room1.txt","w+");
    flock($file_save,LOCK_EX);
    for($line=0;$line<count($room_file);$line++){
    fputs($file_save,$room_file[$line]."\n");
    };
    flock($file_save,LOCK_UN);
    fclose($file_save);
    echo "sentok";
    exit();
    ?>
    Bước 5: Tạo file user.php:

    Mã:
    <?php
     
    function saveUsers($onlineusers_file){
    $file_save=fopen("onlineusers.txt","w+");
    flock($file_save,LOCK_EX);
    for($line=0;$line<count($onlineusers_file);$line++){
    fputs($file_save,$onlineusers_file[$line]."\n");
    };
    flock($file_save,LOCK_UN);
    fclose($file_save);
    }
     
    $onlineusers_file=file("onlineusers.txt",FILE_IGNORE_NEW_LINES);
    if (isset($_POST['user'],$_POST['oper'])){
    $user=$_POST['user'];
    $oper=$_POST['oper'];
    $userexist=in_array($user,$onlineusers_file);
    if ($userexist)$userindex=array_search($user,$onlineusers_file);
     
    if($oper=="signin" && $userexist==false){
    $onlineusers_file[]=$user;
    saveUsers($onlineusers_file);
    echo "signin";
    exit();
    }
     
    if($oper=="signin" && $userexist==true){
    echo "userexist";
    exit();
    }
     
    if($oper=="signout" && $userexist==true){
    array_splice($onlineusers_file,$userindex,1);
    saveUsers($onlineusers_file);
    echo "signout";
    exit();
    }
     
    if($oper=="signout" && $userexist==false){
    echo "usernotfound";
    exit();
    }
    }
    $olu=join("<br>",$onlineusers_file);
    echo $olu;
     
    ?>
    
    Bước 6: Tạo javasript (ajax.js):

    Mã:
    function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){
    var xmlhttp
    try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
    catch(e){
    try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
    catch(e){
    try{xmlhttp=new XMLHttpRequest()}
    catch(e){
    alert("Your Browser Does Not Support AJAX")}}}
     
    err=""
    if (GP==undefined) err="GP "
    if (URL==undefined) err +="URL "
    if (PARAMETERS==undefined) err+="PARAMETERS"
    if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;}
     
    xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState == 4){
    if (RESPONSEFUNCTION=="") return false;
    eval(RESPONSEFUNCTION(xmlhttp.responseText))
    }
    }
     
    if (GP=="GET"){
    URL+="?"+PARAMETERS
    xmlhttp.open("GET",URL,true)
    xmlhttp.send(null)
    }
     
    if (GP="POST"){
    PARAMETERS=encodeURI(PARAMETERS)
    xmlhttp.open("POST",URL,true)
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
    xmlhttp.setRequestHeader("Content-length",PARAMETERS.length)
    xmlhttp.setRequestHeader("Connection", "close")
    xmlhttp.send(PARAMETERS)
    }
    }
    Bước 7: Tạo javascript (chatbox.js):

    Mã:
    lastReceived=0;
     
    // Hide the message form
    function hideShow(hs){
    if(hs=="hide"){
    signInForm.signInButt.value="Sign in"
    signInForm.signInButt.name="signIn"
    messageForm.style.display="none"
    signInForm.userName.style.display="block"
    signInName.innerHTML=""
    }
    if(hs=="show"){
    signInForm.signInButt.value="Sign out"
    signInForm.signInButt.name="signOut"
    messageForm.style.display="block"
    signInForm.userName.style.display="none"
    signInName.innerHTML=signInForm.userName.value
    }
    }
     
     
    // Sign in and Out
    function signInOut(){
    if (signInForm.userName.value=="" || signInForm.userName.value.indexOf(" ")>-1){
    alert("Not valid user name\nPlease make sure your user name didn't contains a space\nOr it's not empty.");
    signInForm.userName.focus();
    return false;
    }
     
    // Sign in
    if (signInForm.signInButt.name=="signIn"){
    data="user=" + signInForm.userName.value +"&oper=signin"
    Ajax_Send("POST","users.php",data,checkSignIn);
    return false
    }
     
    // Sign out
    if (signInForm.signInButt.name=="signOut"){
    data="user=" + signInForm.userName.value +"&oper=signout"
    Ajax_Send("POST","users.php",data,checkSignOut);
    return false
    }
    }
     
    // Sign in response
    function checkSignIn(res){
    if(res=="userexist"){
    alert("The user name you typed is already exist\nPlease try another one");
    return false;
    }
    if(res=="signin"){
    hideShow("show")
     
    messageForm.message.focus()
    updateInterval=setInterval("updateInfo()",3000);
    serverRes.innerHTML="Sign in"
    }
    }
     
    // Sign out response
    function checkSignOut(res){
    if(res=="usernotfound"){
    serverRes.innerHTML="Sign out error";
    res="signout"
    }
    if(res=="signout"){
    hideShow("hide")
    signInForm.userName.focus()
    clearInterval(updateInterval)
    serverRes.innerHTML="Sign out"
    return false
    }
    }
     
    // Update info
    function updateInfo(){
    serverRes.innerHTML="Updating"
    Ajax_Send("POST","users.php","",showUsers)
    Ajax_Send("POST","receive.php","lastreceived="+lastReceived,showMessages)
    }
     
    // update online users
    function showUsers(res){
    usersOnLine.innerHTML=res
    }
     
    // Update messages view
    function showMessages(res){
    serverRes.innerHTML=""
    msgTmArr=res.split("<SRVTM>")
    lastReceived=msgTmArr[1]
    messages=document.createElement("span")
    messages.innerHTML=msgTmArr[0]
    chatBox.appendChild(messages)
    chatBox.scrollTop=chatBox.scrollHeight
    }
     
    // Send message
    function sendMessage(){
    data="message="+messageForm.message.value+"&user="+signInForm.userName.value
    serverRes.innerHTML="Sending"
    Ajax_Send("POST","send.php",data,sentOk)
    }
     
    // Sent Ok
    function sentOk(res){
    if(res=="sentok"){
    messageForm.message.value=""
    messageForm.message.focus()
    serverRes.innerHTML="Sent"
    }
    else{
    serverRes.innerHTML="Not sent"
    }
    }
    Bước 8: tạo 2 file (onlineuser.txt và room1.txt).

    Chúc bạn thành công!
  2. Offline

    veoancol

    • Windows 2.0

    • Đơn giản thôi mà
    Số bài viết:
    60
    Đã được thích:
    26
    Điểm thành tích:
    20

Chia sẻ trang này

Advertising: Linux system admin | nukeviet | nukeviet 4 | Upload ảnh miễn phí