ajax php 聊天室实例代码

2025-09-07

 "欢迎来到迷你ajax聊天室。最新版本 1.2。下载请到www.phprm.com",    //聊天室标题    "title" => "mini ajax chatroom by longbill",    //第一个到聊天室的欢迎    "firstone" => "welcome to longbill's mini ajax chatroom!",    //当信息有禁止内容时显示    "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['touchme'];if (!is_dir($roomdir)) @mkdir($roomdir) or die("error when creating folder $roomdir");$room = $_get['room'];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, '' . " " . time() . "|" . $lang["firstone"] . " ");if (!file_exists($datafile)) @file_put_contents($datafile, '' . " ");$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('http_x_forwarded_for')) $realip = getenv('http_x_forwarded_for');        else if (getenv('http_client_ip')) $realip = getenv('http_client_ip');        else $realip = getenv('remote_addr');    }    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] . ':';        if (is_array($item)) $json.= array2json($item);        else if (is_string($item)) $json.= '"' . str_replace(array(            " ",            " "        ) , "", $item) . '"';        else $json.= $item;    }    $json.= ($isarr) ? "]" : "}";    return $json;}function keeponline() {    global $disonline, $datafile;    if (!$disonline) return;    $name = $_post['name'];    $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['name']));    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['content']);    if (count($arr) > 20) die('error');    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", "ajax php 聊天室实例代码 ", $content);        $content = ($style) ? "{$content}" : $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['name'];    $name = str_replace(" ", "", $name);    $ip = get_ip();    $json = array();    $json["lastmod"] = time();    $item = array();    $newonline = array();    $offline = array();    $fp = @fopen($filename, 'r');    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['name'];    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 {?> 迷你php+ajax聊天室演示 <?php echo $title; ?>   "> <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't support xmlhttprequest");}function pickcolor() {    if (!window.isie)        return;    var scolor = $('dlghelper').choosecolordlg();    var color = scolor.tostring(16);    while (color.length < 6)        color = "0" + color;    window.color = color;    color = "#" + color;    $('p_color').style.backgroundcolor = color;    $('p_color').value = color;}var isie = (document.all && window.activexobject) ? true : false;

loading...

' id='p_online'>loading online...

<script>var debug = 0;var lastmod = < ? php echo time() - $earlier * 60; ? > ;var login = 1;var loading = false;var olduser = getcookie('chatusername');if (olduser != "") $('chat_user').value = olduser;var room = "";var first = 1;var dis = "";var lastword;var color = '';var touchs = ;var dotouch = true;var maxdisplay = ;var nowdisplay = 1;var sending = 0;var loaded_lines = [];var editing = 0;function encode(s) { return (encodeuricomponent) ? encodeuricomponent(s) : s;}$('chat_user').onfocus = setonfocus;$('input_size').onfocus = setonfocus;function setonfocus() { window.editing = 1;}function setonblur() { window.editing = 0;}var keep_ajax;function keeponline() { var name = $('chat_user').value; if (!name) return; keep_ajax = createajax(); keep_ajax.open('post', '', 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('post', '', 0); ajax.setrequestheader("content-type", "application/x-www-form-urlencoded"); ajax.send("action=quit&name=" + encode($('chat_user').value)); //alert("sending close action=quit&name="+encode($('chat_user').value)); //alert("response:"+ajax.responsetext); } else return '';}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 = $('p_contents'); try { if (debug) alert(load_word_ajax.responsetext); eval("var arr = " + load_word_ajax.responsetext); } catch (e) { alert('error 101 json syntax error! ' + 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 p_online = $('p_online'); if (window.first) { body.innerhtml = ""; window.first = false; } if (arr.onlines) { $('p_online').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 p1 = document.createelement("p"); window.nowdisplay++; if (window.nowdisplay > window.maxdisplay) window.nowdisplay = 1; if ($("contentitem" + window.nowdisplay)) body.removechild($("contentitem" + window.nowdisplay)); p1.classname = "content"; p1.id = "contentitem" + window.nowdisplay; p1.innerhtml = line[i].word + " (" + line[i].time + ")"; body.appendchild(p1); 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 ($('chat_word').disabled == false && window.editing != 1) { $('chat_word').focus(); } } }}function load_word_error() { window.loading = false; window.status = 'error 102:while loading words'; settimeout("window.status = '';", 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('post', '', true); load_word_ajax.onreadystatechange = load_word_change; var urlstring = ''; urlstring += "lastmod=" + window.lastmod; urlstring += "&room=" + room; urlstring += "&action=read"; urlstring += "&name=" + encode($('chat_user').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("p"); d1.id = name; d1.innerhtml = name; d1.classname = "online"; $('p_online').appendchild(d1);}touchme();function check_send(e) { if (!e) e = window.event; var obj = $('chat_word'); 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('已经有人使用你的昵称了'); $('chat_user').value = ""; $('chat_user').focus(); } else if (send_ajax.responsetext.indexof("repeat") != -1) { $('chat_word').value = window.lastcontent; } on_send_ok(); if (!window.loading) { window.dotouch = true; load_word(); } $('chat_word').disabled = false; $('chat_word').focus(); }}function on_send_begin() { with ($('chat_word')) { disabled = true; style.backgroundcolor = "#eeeeee"; } window.sending = 1;}function on_send_ok() { window.sending = 0; with ($('chat_word')) { value = ''; disabled = false; focus(); style.backgroundcolor = "#ffffff"; }}function on_send_error() { window.sending = 0; with ($('chat_word')) { disabled = false; focus(); style.backgroundcolor = "#ffffff"; }}function send_ajax_error() { alert('error 103 when send words you can send them again!'); $('chat_word').value = window.lastcontent; window.sending = 0; on_send_error();}function chat_send() { send_ajax = createajax(); send_ajax.open('post', '', true); send_ajax.setrequestheader("content-type", "application/x-www-form-urlencoded"); send_ajax.onreadystatechange = send_ajax_change; var urlstring = ''; var name = $('chat_user').value.replace(" ", ""); var content = $('chat_word').value; var bold = ($('input_bold').checked) ? "bold" : ""; var size = parseint($('input_size').value); var font = $('input_font').value; if (name == "") { alert('please enter your nick name first!!'); $('chat_user').focus(); return; } if (content == "" || content == " " || content == " " || content == " ") { alert('please enter your words!'); $('chat_word').focus(); $('chat_word').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", $('chat_user').value);}function resize(s) { var o = $('p_contents').style; var h = parseint(o.height); h = (s) ? h + 50 : h - 50; if (h <= 50 || h >= 3000) return; o.height = h; $('p_contents').scrolltop = 655350;}function clearall() { $('p_contents').innerhtml = "";}


标签: 迷你聊天室

本文地址:https://www.lifejia.cn/news/208840.html

免责声明:本站内容仅用于学习参考,信息和图片素材来源于互联网,如内容侵权与违规,请联系我们进行删除,我们将在三个工作日内处理。联系邮箱:cloudinto#qq.com(把#换成@)