php教程 php手册 ajax php 聊天室实例代码

ajax php 聊天室实例代码

May 25, 2016 pm 04:57 PM
fopen

<?php
/*
ajax php 聊天室实例代码
但是必须基于以下条款:
* 署名。你必须明确标明作者的名字。.
* 非商业用途。 你不可将当前作品用于商业目的。
* 保持一致。 如果你基于当前作品更改、变换或构造新作品,你应当按照与当前协议完全相同的协议分发最终作品
* 对于任何二次使用或分发,你必须让其他人明确当前作品的授权条款
* 在得到作者的明确允许下,这里的某些条款可以放弃
此约定是法律文本 (完整的协议)的简单易读概要 
****************************************/
//****************参数设置****************
//显示在线用户
$disonline = true;
//新登陆时显示最近内容的条数(默认为30条)
$leastnum = 30;
//默认的房间名(默认是每天换一个文件),如果去掉d,则是每月换一个文件
$room = date("y-m-d");
//房间保存路径,必须以/结尾
$roomdir = "rooms/";
//编码方式
$charset = "utf-8";
//客户端最大显示内容条数(建议不要太大)
$maxdisplay = 300;
//语言
$lang = array(
    //聊天室描述
    "description" => "欢迎来到迷你ajax聊天室。最新版本 1.2。下载请到<a href=&#39;http://phprm.com&#39; target=_blank>www.phprm.com</a>",
    //聊天室标题
    "title" => "mini ajax chatroom by longbill",
    //第一个到聊天室的欢迎
    "firstone" => "<span style=&#39;color:#16a5e9;&#39;>welcome to longbill&#39;s mini ajax chatroom!</span>",
    //当信息有禁止内容时显示
    "ban" => "i am a pig!",
    //关键字
    "keywords" => "聊天室,迷你,小型,ajax,chat,chatroom,longbill,phprm.com,php,网页特效",
    //发言提示
    "hereyourwords" => "在这里发言!"
);
error_reporting(e_all ^ e_notice ^ e_warning);
header("content-type:text/html; charset=utf-8");
$get_past_sec = 3; //如果发现丢话,可以适当调大这个值
$touchs = 10; //检查在线人数的时间间隔
if (!function_exists("file_get_contents")) {
    function file_get_contents($path) {
        if (!file_exists($path)) return false;
        $fp = @fopen($path, "r");
        $all = fread($fp, filesize($path));
        fclose($fp);
        return $all;
    }
}
if (!function_exists("file_put_contents")) {
    function file_put_contents($path, $val) {
        $fp = @fopen($path, "w");
        fputs($fp, $val);
        fclose($fp);
        return true;
    }
}
$title = $lang["title"];
$earlier = 10;
$description = $lang["description"];
$origroom = $room;
$least = ($_get["dis"]) ? intval($_get["dis"]) : $leastnum;
$touchme = $_post[&#39;touchme&#39;];
if (!is_dir($roomdir)) @mkdir($roomdir) or die("error when creating folder $roomdir");
$room = $_get[&#39;room&#39;];
if (!$room) $room = $_post["room"];
$room = checkfilename($room);
if (!$room) $room = $origroom;
$filename = $roomdir . $room . ".dat.php";
$datafile = $roomdir . $room . ".php";
if (!file_exists($filename)) @file_put_contents($filename, &#39;<?php die();?>&#39; . " " . time() . "|" . $lang["firstone"] . " ");
if (!file_exists($datafile)) @file_put_contents($datafile, &#39;<?php die();?>&#39; . " ");
$action = $_post["action"];
function checkfilename($file) {
    if (!$file) return "";
    $file = trim($file);
    $a = substr($file, -1);
    $file = eregi_replace("^[./]*", "", $file);
    $file = eregi_replace("[./]*$", "", $file);
    $arr = array(
        "../",
        "./",
        "/",
        "",
        "..",
        "."
    );
    $file = str_replace($arr, "", $file);
    return $file;
}
function get_ip() {
    global $_server;
    if ($_server) {
        if ($_server[http_x_forwarded_for]) $realip = $_server["http_x_forwarded_for"];
        else if ($_server["http_client_ip"]) $realip = $_server["http_client_ip"];
        else $realip = $_server["remote_addr"];
    } else {
        if (getenv(&#39;http_x_forwarded_for&#39;)) $realip = getenv(&#39;http_x_forwarded_for&#39;);
        else if (getenv(&#39;http_client_ip&#39;)) $realip = getenv(&#39;http_client_ip&#39;);
        else $realip = getenv(&#39;remote_addr&#39;);
    }
    return $realip;
}
function array2json($arr) {
    $keys = array_keys($arr);
    $isarr = true;
    $json = "";
    for ($i = 0; $i < count($keys); $i++) {
        if ($keys[$i] !== $i) {
            $isarr = false;
            break;
        }
    }
    $json = $space;
    $json.= ($isarr) ? "[" : "{";
    for ($i = 0; $i < count($keys); $i++) {
        if ($i != 0) $json.= ",";
        $item = $arr[$keys[$i]];
        $json.= ($isarr) ? "" : $keys[$i] . &#39;:&#39;;
        if (is_array($item)) $json.= array2json($item);
        else if (is_string($item)) $json.= &#39;"&#39; . str_replace(array(
            " ",
            " "
        ) , "", $item) . &#39;"&#39;;
        else $json.= $item;
    }
    $json.= ($isarr) ? "]" : "}";
    return $json;
}
function keeponline() {
    global $disonline, $datafile;
    if (!$disonline) return;
    $name = $_post[&#39;name&#39;];
    $ip = get_ip();
    $onlines = @file_get_contents($datafile);
    $s1 = "|{$name}|{$ip}|";
    if (strpos($onlines, $s1) === false) {
        if (strpos($onlines, "|" . $name . "|") === false) {
            $fp = @fopen($datafile, "a+");
            if ($fp) {
                if (@flock($fp, lock_ex)) {
                    @fputs($fp, time() . "|" . time() . $s1 . " ");
                    @flock($fp, lock_un);
                }
                @fclose($fp);
            }
        } else {
            echo "name";
            die();
        }
    }
}
if ($action == "write") {
    $color = $_post["color"];
    if (!eregi("[0-9a-fa-f]{6}", $color) || $color == "#000000") $color = "";
    $color = "#" . $color;
    $size = intval($_post["size"]);
    $name = htmlspecialchars(str_replace(array(
        " ",
        " "
    ) , "", $_post[&#39;name&#39;]));
    if (!$name) die("no name!!");
    $ip = get_ip();
    keeponline();
    $s = "";
    $style = "";
    $font = $_post["font"];
    if ($font == "songti") $font = "宋体";
    else if ($font == "heiti") $font = "黑体";
    else if ($font == "kaiti") $font = "楷体_gb2312";
    else $font = "";
    $style.= (!$font) ? "" : "font-family:" . $font . ";";
    $style.= (!$_post["bold"]) ? "" : "font-weight:bold;";
    $style.= (!$color || $color == "#") ? "" : "color:{$color};";
    $style.= (!$size || $size == "16") ? "" : "font-size:{$size}px;";
    $t = time();
    $arr = explode(" ", $_post[&#39;content&#39;]);
    if (count($arr) > 20) die(&#39;error&#39;);
    for ($i = 0; $i < count($arr); $i++) {
        $content = $arr[$i];
        $content = trim($content);
        $content = str_replace(array(
            " ",
            " "
        ) , "", $content);
        if (!$content) continue;
        $content = htmlspecialchars($content);
        $content = preg_replace("~[img](http://[a-za-z0-9.-_+%?]*)[/img]~i", "<img  src=&#39;$1&#39; / alt="ajax php 聊天室实例代码 " >", $content);
        $content = ($style) ? "<span style=&#39;{$style}&#39;>{$content}</span>" : $content;
        $s.= $t . "|" . $name . ":" . $content . " ";
    }
    if (!$s) die("no content!!");
    $fp = @fopen($filename, "a+");
    if (!$fp) die("repeat");
    $re_time = 0;
    while (!@flock($fp, lock_ex)) {
        sleep(1);
        $re_time++;
        if ($re_time >= 4) break;
    }
    if ($re_time < 4) {
        @fputs($fp, $s);
        @flock($fp, lock_un);
    } else die("repeat");
    @fclose($fp);
    echo "ok";
} else if ($action == "read") {
    $first = $_post["first"];
    $lastmod = intval($_post["lastmod"]) - $get_past_sec; //得到两秒以内的所有发言,
    $alastmod = @filemtime($filename);
    if ($lastmod - $alastmod > 360 * 48) die;
    $name = $_post[&#39;name&#39;];
    $name = str_replace(" ", "", $name);
    $ip = get_ip();
    $json = array();
    $json["lastmod"] = time();
    $item = array();
    $newonline = array();
    $offline = array();
    $fp = @fopen($filename, &#39;r&#39;);
    flock($fp, lock_ex);
    $s = fread($fp, filesize($filename));
    flock($fp, lock_un);
    fclose($fp);
    $lines = explode(" ", $s);
    if ($alastmod >= $lastmod && !$first) {
        foreach ($lines as $l) {
            $item2 = array();
            $l = str_replace(array(
                " ",
                " "
            ) , "", $l);
            if (strpos($l, "|") === false) continue;
            $arr = explode("|", $l);
            $t = intval($arr[0]);
            if ($t >= $lastmod) {
                $item2["time"] = date("h:i:s", $t);
                $item2["word"] = addslashes($arr[1]);
                $item[] = $item2;
            }
        }
    } else if ($first) {
        $item = array();
        $total = count($lines);
        for ($i = $total - 1; $i >= $total - $least; $i--) {
            if ($i <= 0) break;
            $item2 = array();
            $l = str_replace(array(
                " ",
                " "
            ) , "", $lines[$i]);
            if (strpos($l, "|") === false) continue;
            $arr = explode("|", $l);
            $t = intval($arr[0]);
            $item2["time"] = (date("m-d", time()) == date("m-d", $t)) ? date("h:i:s", $t) : date("m-d h:i", $t);
            $item2["word"] = addslashes($arr[1]);
            $item[] = $item2;
        }
        $item = array_reverse($item);
    }
    $s = "";
    $nt = time();
    $onlines = array();
    if ($disonline && $touchme) {
        $users = @file($datafile);
        foreach ($users as $l) {
            $l = str_replace(array(
                " ",
                " "
            ) , "", $l);
            if (strpos($l, "|") === false) {
                $s.= $l . " ";
                continue;
            }
            $arr = explode("|", $l);
            if ($nt - intval($arr[1]) < $touchs * 3) {
                if (trim($name) == trim($arr[2])) {
                    $s.= $arr[0] . "|" . time() . "|" . $name . "|" . get_ip() . "| ";
                } else $s.= $l . " ";
                $onlines[] = htmlspecialchars($arr[2]);
            }
        }
        @file_put_contents($datafile, $s);
        $json["onlines"] = $onlines;
    }
    $json["lines"] = $item;
    echo array2json($json);
} else if ($action == "keep") {
    keeponline();
    echo "keep ok";
} else if ($action == "quit") {
    $name = $_post[&#39;name&#39;];
    if ($disonline) {
        $users = @file($datafile);
        foreach ($users as $l) {
            $l = str_replace(array(
                " ",
                " "
            ) , "", $l);
            if (strpos($l, "|") === false) {
                $s.= $l . " ";
                continue;
            }
            $arr = explode("|", $l);
            if (trim($name) == trim($arr[2])) continue;
            else $s.= $l . " ";
        }
        @file_put_contents($datafile, $s);
        echo "ok";
    }
    die();
} else {
?>
<html>
<head>
 <title>迷你php+ajax聊天室演示 <?php echo $title; ?></title>
 <meta http-equiv=&#39;pragma&#39; content=&#39;no-cache&#39; />
 <meta http-equiv=content-type content="text/html; charset=<?php echo $charset; ?>" />
 <meta name="keywords" content="<?php echo $lang["keywords"]; ?>">
 <meta name="description" content="mini ajax chatroom by longbill. <?php echo $description; ?>">
<style type=&#39;text/css&#39;>
body { text-align:center; color:#333333; font-size:12px; font-family:宋体;}
a { text-decoration:none; color:#a2b700; }
.mydiv { text-align:left; margin:5px; padding:5px; border:1px solid #ff8c05; background-color:#fdd283; width:600px; }
.inputtext { border:0px; border-bottom:1px solid #333333; background-color:transparent;}
.submit { border:1px solid #ff8c05; background-color:transparent; }
.contents { border:1px solid #ff8c05;margin:5px; margin-top:10px;background-color:#ffffff; overflow:auto;word-break:break-all;word-wrap :break-word;}
.bg { background-color:#ffffff; }
.content { border:0px;background-color:transparent;width:auto; font-size:16px; font-family:fixedsys; margin:2px; padding:1px; }
.time { color:#aaaaaa; font-size:10px; font-family:arial;}
.online { margin:5px; padding:0px; display:inline; }
.mybut { width:20px; height:20px; background-color:#ff8c05; text-align:center; font-size:18px; color: #333333;}
</style>
<script>
function $(obj) {
    return document.getelementbyid(obj);
}
function setcookie(name, value, t) {
    var cookieexp = 5 * 30 * 24 * 60 * 60 * 1000; //5 months
    var cookiestr = name + "=" + escape(value) + ";";
    var expires = "";
    var d = new date();
    var t2 = (!t) ? cookieexp : t * 60 * 1000;
    d.settime(d.gettime() + cookieexp);
    expires = "expires=" + d.togmtstring() + ";";
    document.cookie = cookiestr + expires;
}
function getcookie(name) {
    var start = document.cookie.indexof(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length)))
        return "";
    if (start == -1)
        return "";
    var end = document.cookie.indexof(";", len);
    if (end == -1)
        end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}
function createajax() {
    if (window.xmlhttprequest) {
        var ohttp = new xmlhttprequest();
        return ohttp;
    } else if (window.activexobject) {
        var versions = [
            "msxml2.xmlhttp.6.0",
            "msxml2.xmlhttp.3.0"
        ];
        for (var i = 0; i < versions.length; i++) {
            try {
                var ohttp = new activexobject(versions[i]);
                return ohttp;
            } catch (error) {}
        }
    }
    throw new error("your browser doesn&#39;t support xmlhttprequest");
}
function pickcolor() {
    if (!window.isie)
        return;
    var scolor = $(&#39;dlghelper&#39;).choosecolordlg();
    var color = scolor.tostring(16);
    while (color.length < 6)
        color = "0" + color;
    window.color = color;
    color = "#" + color;
    $(&#39;div_color&#39;).style.backgroundcolor = color;
    $(&#39;div_color&#39;).value = color;
}
var isie = (document.all && window.activexobject) ? true : false;
</script>
</head>
<body >
<center>
<div class=mydiv style=&#39;text-align:center; border:0px; background-color:transparent; font-size:25px; color:#ff8c05;&#39;><?php echo $title; ?></div>
<div class="mydiv login" id=&#39;div_description&#39;>
<?php
    echo $description; ?>
</div>
<div class="mydiv rooms" id=&#39;div_msg&#39;>
<div class=&#39;contents&#39; style=&#39;height:350px;&#39; id=&#39;div_contents&#39;>loading...</div>
</div>
<div class="mydiv login" id=&#39;div_name&#39; style=&#39;display:block;&#39;>
name:<input type=text class="inputtext bg" size=8 id=&#39;chat_user&#39; value=&#39;&#39; maxlength=30 /> 
<object id=dlghelper classid="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" width="0px" height="0px"></object>
<input class="inputtext" style=&#39;width:50px;cursor:hand;10px;background-color:#000000;color:#ffffff;&#39; id=&#39;div_color&#39; onclick="pickcolor()" value="#000000" onblur="this.style.backgroundcolor=this.value;window.color=this.value.replace(&#39;#&#39;,&#39;&#39;);" />
 size:<input class="inputtext bg" type=text style=&#39;width:20px&#39; maxlength=3 id=&#39;input_size&#39; value=&#39;16&#39; />(px)
 font:<select id=&#39;input_font&#39; class=&#39;inputtext bg&#39; style=&#39;width:70px;&#39;>
<option value=&#39;fixedsys&#39;>fixedsys</option>
<option value=&#39;heiti&#39;>黑体</option>
<option value=&#39;songti&#39;>宋体</option>
<option value=&#39;kaiti&#39;>楷体</option>
</select>
bold:<input type=checkbox id=&#39;input_bold&#39; class=&#39;inputtext&#39; style=&#39;border-bottom:0px;&#39; />
window:<a class=&#39;mybut&#39; href=&#39;#&#39; onclick=&#39;resize(1)&#39;>+</a>
 <a class=&#39;mybut&#39; href=&#39;#&#39; onclick=&#39;resize(0)&#39;>-</a>
 <a class=&#39;mybut&#39; style=&#39;width:25px;font-size:16px;&#39; href=&#39;#&#39; onclick=&#39;clearall()&#39;>clear</a>
</div>
<div class="mydiv login" id=&#39;div_word&#39;>
<textarea type=text class="inputtext bg" rows=1 scrolling=no style=&#39;height:20px;overflow:hidden;width:500px;&#39; id=&#39;chat_word&#39; onfocus="if (this.value == &#39;<?php echo $lang["hereyourwords"]; ?>&#39;) this.value=&#39;&#39;; window.editing=0; " 
 onkeydown="return check_send(event);" ><?php echo $lang["hereyourwords"]; ?></textarea>
<input type=button class=submit value=&#39;send&#39; onclick="chat_send();$(&#39;chat_word&#39;).style.height=20;" onfocus="this.blur();"/>
</div>
<div class=&#39;mydiv&#39; style=&#39;display:<?php
    if (!$disonline) echo "none"; ?>&#39; id=&#39;div_online&#39;>loading online...</div>
<script>
var debug = 0;
var lastmod =  <  ? php echo time() - $earlier * 60;
 ?  > ;
var login = 1;
var loading = false;
var olduser = getcookie(&#39;chatusername&#39;);
if (olduser != "")
    $(&#39;chat_user&#39;).value = olduser;
var room = "<?php echo $room; ?>";
var first = 1;
var dis = "<?php echo $least; ?>";
var lastword;
var color = &#39;&#39;;
var touchs =  <?php echo $touchs;?> ;
var dotouch = true;
var maxdisplay =  <?php echo $maxdisplay;?> ;
var nowdisplay = 1;
var sending = 0;
var loaded_lines = [];
var editing = 0;
function encode(s) {
    return (encodeuricomponent) ? encodeuricomponent(s) : s;
}
$(&#39;chat_user&#39;).onfocus = setonfocus;
$(&#39;input_size&#39;).onfocus = setonfocus;
function setonfocus() {
    window.editing = 1;
}
function setonblur() {
    window.editing = 0;
}
var keep_ajax;
function keeponline() {
    var name = $(&#39;chat_user&#39;).value;
    if (!name)
        return;
    keep_ajax = createajax();
    keep_ajax.open(&#39;post&#39;, &#39;<?php echo basename(__file__); ?>&#39;, 1);
    keep_ajax.setrequestheader("content-type", "application/x-www-form-urlencoded");
    keep_ajax.onreadystatechange = function () {
        if (keep_ajax.readystate == 4 && keep_ajax.status == 200) {
            //alert(keep_ajax.responsetext);
        }
    }
    keep_ajax.send("action=keep&name=" + encode(name));
}
setinterval("keeponline()", touchs * 1000);
function quitroom() {
    if (confirm("你真的要离开聊天室吗?")) {
        var ajax = createajax();
        ajax.open(&#39;post&#39;, &#39;<?php echo basename(__file__); ?>&#39;, 0);
        ajax.setrequestheader("content-type", "application/x-www-form-urlencoded");
        ajax.send("action=quit&name=" + encode($(&#39;chat_user&#39;).value));
        //alert("sending close  action=quit&name="+encode($(&#39;chat_user&#39;).value));
        //alert("response:"+ajax.responsetext);
    } else
        return &#39;&#39;;
}
document.body.onbeforeunload = quitroom;
setinterval(" load_word()", (debug) ? 6000 : 1000);
var load_word_ajax;
//下载完成后的处理函数
function load_word_change() {
    if (load_word_ajax.readystate == 4) {
        if (load_word_ajax.status != 200) {
            load_word_error();
            return;
        }
        window.loading = false;
        var body = $(&#39;div_contents&#39;);
        try {
            if (debug)
                alert(load_word_ajax.responsetext);
            eval("var arr = " + load_word_ajax.responsetext);
        } catch (e) {
            alert(&#39;error 101 json syntax error! &#39; + load_word_ajax.responsetext);
            return;
        }
        if (!arr || !arr.lastmod || typeof(arr.lastmod) == "undefined") {
            return;
        }
        var html = "";
        var line = arr.lines;
        var i = 0;
        var v1 = 0;
        var div_online = $(&#39;div_online&#39;);
        if (window.first) {
            body.innerhtml = "";
            window.first = false;
        }
        if (arr.onlines) {
            $(&#39;div_online&#39;).innerhtml = "";
            for (var i = 0; i < arr.onlines.length; i++)
                addonline(arr.onlines[i]);
        }
        for (var i = 0; i < line.length; i++) {
            var linekey = line[i].word.substring(line[i].word.length - 20, line[i].word.length) + line[i].time;
            if (window.loaded_lines[linekey] === true) {
                if (debug)
                    alert("jump:" + linekey);
                continue;
            }
            var div1 = document.createelement("div");
            window.nowdisplay++;
            if (window.nowdisplay > window.maxdisplay)
                window.nowdisplay = 1;
            if ($("contentitem" + window.nowdisplay))
                body.removechild($("contentitem" + window.nowdisplay));
            div1.classname = "content";
            div1.id = "contentitem" + window.nowdisplay;
            div1.innerhtml = line[i].word + " <span class=&#39;time&#39;>(" + line[i].time + ")</span>";
            body.appendchild(div1);
            window.loaded_lines[linekey] = true;
            body.scrolltop = 655350;
            v1 = 1;
        }
        if (v1) {
            window.focus();
            document.body.focus();
            window.lastmod = arr.lastmod;
            if (debug)
                alert("lastmod = " + arr.lastmod + " window.lastmod=" + window.lastmod);
            if ($(&#39;chat_word&#39;).disabled == false && window.editing != 1) {
                $(&#39;chat_word&#39;).focus();
            }
        }
    }
}
function load_word_error() {
    window.loading = false;
    window.status = &#39;error 102:while loading words&#39;;
    settimeout("window.status = &#39;&#39;;", 5000);
}
function load_word() {
    load_word_ajax = createajax();
    if (window.loading) {
        try {
            load_word_ajax.abort();
            window.loading = false;
        } catch (e) {}
    }
    if (!window.lastmod) {
        alert("window.lastmod=" + window.lastmod);
        return;
    }
    load_word_ajax.open(&#39;post&#39;, &#39;<?php echo basename(__file__); ?>&#39;, true);
    load_word_ajax.onreadystatechange = load_word_change;
    var urlstring = &#39;&#39;;
    urlstring += "lastmod=" + window.lastmod;
    urlstring += "&room=" + room;
    urlstring += "&action=read";
    urlstring += "&name=" + encode($(&#39;chat_user&#39;).value);
    if (window.first) {
        urlstring += "&first=true";
        urlstring += "&dis=" + dis;
    }
    //如果到了取得在线用户的时间
    if (window.dotouch) {
        urlstring += "&touchme=true";
        window.dotouch = false;
        //垃圾内存回收
        try {
            collectgarbage();
        } catch (e) {}
    }
    window.loading = true;
    if (debug)
        alert("sending:" + urlstring);
    load_word_ajax.setrequestheader("content-type", "application/x-www-form-urlencoded");
    load_word_ajax.send(urlstring);
}
function touchme() {
    window.dotouch = true;
    settimeout("touchme()", window.touchs * 1000);
}
function showalert(a, n) {
    if (!n)
        n = 0;
    if (n > 3)
        return;
    if (!a) {
        a = 0;
        b = 1;
    } else {
        a = 1;
        b = 0;
    }
    document.title = mytitle[a];
    settimeout("showalert(" + b + "," + (n + 1) + ");", 500);
}
function addonline(name) {
    if ($(name))
        return;
    var d1 = document.createelement("div");
    d1.id = name;
    d1.innerhtml = name;
    d1.classname = "online";
    $(&#39;div_online&#39;).appendchild(d1);
}
touchme();
function check_send(e) {
    if (!e)
        e = window.event;
    var obj = $(&#39;chat_word&#39;);
    if (isie)
        obj.style.height = obj.scrollheight + 3;
    if (e.keycode == 13) {
        if ((!e.shiftkey && !e.altkey && !e.ctrlkey) || !isie) {
            chat_send();
            obj.style.height = 20;
            return false;
        } else if (isie)
            obj.style.height = obj.scrollheight + 18;
    }
    return true;
}
var send_ajax;
send_ajax_change = function () {
    if (send_ajax.readystate == 4) {
        if (send_ajax.status != 200) {
            send_ajax_error();
            return;
        }
        if (debug)
            alert("send_ajax response:" + send_ajax.responsetext);
        if (send_ajax.responsetext.indexof("name") != -1) {
            alert(&#39;已经有人使用你的昵称了&#39;);
            $(&#39;chat_user&#39;).value = "";
            $(&#39;chat_user&#39;).focus();
        } else if (send_ajax.responsetext.indexof("repeat") != -1) {
            $(&#39;chat_word&#39;).value = window.lastcontent;
        }
        on_send_ok();
        if (!window.loading) {
            window.dotouch = true;
            load_word();
        }
        $(&#39;chat_word&#39;).disabled = false;
        $(&#39;chat_word&#39;).focus();
    }
}
function on_send_begin() {
    with ($(&#39;chat_word&#39;)) {
        disabled = true;
        style.backgroundcolor = "#eeeeee";
    }
    window.sending = 1;
}
function on_send_ok() {
    window.sending = 0;
    with ($(&#39;chat_word&#39;)) {
        value = &#39;&#39;;
        disabled = false;
        focus();
        style.backgroundcolor = "#ffffff";
    }
}
function on_send_error() {
    window.sending = 0;
    with ($(&#39;chat_word&#39;)) {
        disabled = false;
        focus();
        style.backgroundcolor = "#ffffff";
    }
}
function send_ajax_error() {
    alert(&#39;error 103 when send words you can send them again!&#39;);
    $(&#39;chat_word&#39;).value = window.lastcontent;
    window.sending = 0;
    on_send_error();
}
function chat_send() {
    send_ajax = createajax();
    send_ajax.open(&#39;post&#39;, &#39;<?php echo basename(__file__); ?>&#39;, true);
    send_ajax.setrequestheader("content-type", "application/x-www-form-urlencoded");
    send_ajax.onreadystatechange = send_ajax_change;
    var urlstring = &#39;&#39;;
    var name = $(&#39;chat_user&#39;).value.replace(" ", "");
    var content = $(&#39;chat_word&#39;).value;
    var bold = ($(&#39;input_bold&#39;).checked) ? "bold" : "";
    var size = parseint($(&#39;input_size&#39;).value);
    var font = $(&#39;input_font&#39;).value;
    if (name == "") {
        alert(&#39;please enter your nick name first!!&#39;);
        $(&#39;chat_user&#39;).focus();
        return;
    }
    if (content == "" || content == " " || content == " " || content == " ") {
        alert(&#39;please enter your words!&#39;);
        $(&#39;chat_word&#39;).focus();
        $(&#39;chat_word&#39;).value = "";
        return;
    }
    if (size > 100)
        size = 100;
    else if (size < 0)
        size = 1;
    urlstring += "action=write";
    urlstring += "&name=" + encode(name);
    urlstring += "&content=" + encode(content);
    urlstring += "&bold=" + bold;
    urlstring += "&color=" + window.color;
    urlstring += "&size=" + size;
    urlstring += "&font=" + font;
    urlstring += "&room=" + room;
    window.sending = 1;
    window.lastcontent = content;
    on_send_begin();
    if (debug)
        alert("sending:" + urlstring);
    send_ajax.send(urlstring);
    settimeout("if (window.sending) send_ajax.abort(); on_send_error();", 5000);
    setcookie("chatusername", $(&#39;chat_user&#39;).value);
}
function resize(s) {
    var o = $(&#39;div_contents&#39;).style;
    var h = parseint(o.height);
    h = (s) ? h + 50 : h - 50;
    if (h <= 50 || h >= 3000)
        return;
    o.height = h;
    $(&#39;div_contents&#39;).scrolltop = 655350;
}
function clearall() {
    $(&#39;div_contents&#39;).innerhtml = "";
}
</script>
</center>
</body>
</html>
<?php
}
?>
로그인 후 복사


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

PHP 경고 해결 방법: fopen(): X 라인의 file.php에서 SSL 작업이 실패했습니다. PHP 경고 해결 방법: fopen(): X 라인의 file.php에서 SSL 작업이 실패했습니다. Aug 25, 2023 am 09:22 AM

PHPWarning:fopen():SSLOperationfailedinfile.phponlineX 해결 방법 PHP 프로그래밍에서는 fopen 함수를 사용하여 파일이나 URL을 열고 관련 작업을 수행하는 경우가 많습니다. 그러나 fopen 함수를 사용할 때 때때로 Warning:fopen():SSLOperationfailedinfile.p와 유사한 문제가 발생할 수 있습니다.

PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 권한이 거부되었습니다. PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 권한이 거부되었습니다. Aug 20, 2023 pm 01:45 PM

PHPWarning:fopen():failedtoopenstream:Permissiondenied 문제 해결 방법 PHP 프로그램을 개발하는 과정에서 PHPWarning:fopen():failedtoopenstream:Permissiondenied와 같은 오류 메시지를 자주 접하게 됩니다. 이 오류는 일반적으로 잘못된 파일 또는 디렉터리 권한으로 인해 발생합니다.

PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 해당 파일이나 디렉터리가 없습니다. PHP 경고 해결 방법: fopen(): 스트림을 열지 못했습니다: 해당 파일이나 디렉터리가 없습니다. Aug 19, 2023 am 10:44 AM

PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory 해결 방법 PHP 개발을 사용하는 과정에서 "PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectory"와 같은 파일 작업 문제가 종종 발생합니다.

Matlab에서 fopen 함수 사용 Matlab에서 fopen 함수 사용 Nov 28, 2023 am 11:03 AM

Matlab에서 fopen 함수는 파일을 열고 파일에 대한 후속 읽기 또는 쓰기 작업을 위해 파일 식별자를 반환하는 데 사용됩니다. 필요에 따라 적절한 권한 옵션을 선택하여 파일을 열고 작업이 완료되면 즉시 파일을 닫습니다. 파일을 연 후에는 시스템 리소스를 해제하는 데 더 이상 필요하지 않은 시간에 파일이 닫히는지 확인해야 합니다. 또한 파일 열기에 실패하거나 작업 오류가 발생하는 경우 오류 처리 메커니즘을 사용하여 그에 따라 처리할 수 있습니다.

C 언어에서는 fopen() 함수를 사용하여 쓰기 모드로 기존 파일을 엽니다. C 언어에서는 fopen() 함수를 사용하여 쓰기 모드로 기존 파일을 엽니다. Aug 27, 2023 pm 10:33 PM

C의 fopen() 메소드는 지정된 파일을 여는 데 사용됩니다. 문제 구문 FILE*fopen(filename,mode)을 이해하기 위해 예를 들어 보겠습니다. 다음은 fopen()을 사용하여 파일을 여는 데 유효한 모드입니다: 'r', 'w', 'a', 'r+', 'w+ ', 'a+'. 자세한 내용은 C 라이브러리 함수 fopen()을 참조하세요.

如何解决PHP 경고: fopen(): 스트림을 열지 못했습니다: X 라인의 file.php에 해당 파일이나 디렉터리가 없습니다. 如何解决PHP 경고: fopen(): 스트림을 열지 못했습니다: X 라인의 file.php에 해당 파일이나 디렉터리가 없습니다. Aug 26, 2023 pm 12:46 PM

PHPWarning:fopen():failedtoopenstream:Nosuchfileordirectoryinfile.phponlineX를 해결하는 방법 PHP 프로그램을 개발하고 실행할 때 때때로 PHPWarning:fopen():failedtoopenstream:Nosuchfileor가 발생합니다.

파일 작업을 위해 PHP에서 fopen, fwrite 및 fclose를 사용하는 방법은 무엇입니까? 파일 작업을 위해 PHP에서 fopen, fwrite 및 fclose를 사용하는 방법은 무엇입니까? Jun 01, 2023 am 08:46 AM

PHP 개발에서는 파일 작업이 매우 일반적입니다. 정상적인 상황에서는 파일 읽기, 쓰기, 삭제 및 기타 작업을 수행해야 합니다. 그 중 fopen 함수, fread 함수를 사용하여 파일을 읽을 수 있고, fopen 함수, fwrite 함수, fclose 함수를 사용하여 파일을 쓸 수 있습니다. 이 기사에서는 PHP가 fopen, fwrite 및 fclose를 사용하여 파일 작업을 수행하는 방법을 소개합니다. 1. fopen 함수 fopen 함수는 파일을 여는 데 사용됩니다. r은 다음과 같습니다.

PHP에서 fopen 함수의 사용법은 무엇입니까 PHP에서 fopen 함수의 사용법은 무엇입니까 Sep 18, 2021 pm 03:43 PM

PHP에서 fopen 함수의 사용법은 "fopen(filename, mode, include_path, context)"입니다. fopen() 함수는 파일이나 URL을 여는 데 사용됩니다. 실패하면 오류 메시지와 함께 false를 반환합니다.

See all articles