值得分享的php+ajax实时聊天室


Posted in PHP onJuly 20, 2016

非常经典的一款php+ajax实时聊天室,其中使用PHP文件保存聊天记录,按天划分,PHP实现聊天的功能只有一个文件,整合了PHP与AJAX技术,也就是说只要运行这一个文件就可以启动PHP的聊天室了,关于代码上面也是非常的简单,但是实现了聊天室一般的功能,聊天时的昵称,更改昵称的颜色,聊天字号大小,字体,加粗,窗体的变大变小等等,如果你想搞个聊天室来玩玩,这个源码完全可以满足普通的需求。

具体的效果看如下图:

值得分享的php+ajax实时聊天室

关键代码:

<?php
header('content-type:text/html;charset=utf-8');
//显示在线用户
$disonline = 1;
//新登陆时显示最近内容的条数(默认为30条)
$leastnum = 30;
//默认的房间名(默认是每天换一个文件),如果去掉d,则是每月换一个文件
$room = date("Y-m-d");
//房间保存路径,必须仿quot;/"结尾,可以丿quot;../",等
$roomdir = "rooms/";
//编码方式
$charset = "UTF-8";
//客户端最大显示内容条数(建议不要太大)
$maxdisplay = 300;
//语言包
$lang = array(
//聊天室描述
"description"=>"聊天室.", 
//聊天室标题
"title"=>"Welcome...!",
//第一个到聊天室的欢迎
"firstone"=>"<span style='font-size:16px;color:blue;'>Welcome...!</span>", 
//当信息有禁止内容时显示
"ban" => array('法轮功', '共产党', '李洪志', 'fuck', '叼', '你妈的', '他妈的'),
//关键字
"keywords"=>"Welcome...!",
//发言提示
"hereyourwords" => "在这里发言!"
);

$touchs = 10;
$title = $lang["title"];
$earlier = 10;
$description = $lang["description"];
$origroom = $room;
$least = ($_GET["dis"])?intval($_GET["dis"]):$leastnum;
if ($_GET["room"]) $room = $_GET["room"];
$room = checkfilename($room);
if (!$room) $room = $origroom;
$filename = $roomdir.$room.".dat.php";
$datafile = $roomdir.$room.".php";

if (!is_dir($roomdir)) {
 @mkdir($roomdir, 0777) or exit('no this dir.');
}
if(file_exists($filename)){
 if ((int)filemtime($filename) + 1800 < time()) {
 unlink($filename);
 }
}

if (!file_exists($filename)) @file_put_contents($filename,'<?php die();?>'."\n".time()."|".$lang["firstone"]."\n");
if (!file_exists($datafile)) @file_put_contents($datafile,'<?php die();?>'."\n");
$action = $_GET["action"];

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;
 }
}

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)
{
 if (function_exists('json_encode')) return json_encode($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("\r","\n"),"",$item).'"';
 else $json.=$item;
 }
 $json.= ($isarr)?"]":"}";
 return $json;
}

if ($action == "write")
{
 $color = $_GET['color'];
 if (!eregi("[0-9a-fA-F]{6}",$color) || $color == "#000000") $color = "";
 $color = "#".$color;
 $size = intval($_GET["size"]);
 $arr = @file("php://input");
 $name = str_replace(array("\n","\r"),"",$arr[0]);
 $ip = get_ip();
 if ($disonline)
 {
 $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."\n");
 @flock($fp, LOCK_UN);
 }
 @fclose($fp);
 }
 }
 else
 {
 echo "NAME";
 die();
 }
 }
 }

 $s = "";
 $style = "";
 $font = $_GET["font"];
 if ($font == "songti") $font = "宋体";
 else if ($font == "heiti") $font = "黑体";
 else if ($font == "kaiti") $font = "楷体_GB2312";
 else $font = "";
 $style .= (!$font)?"":"font-family:".$font.";";
 $style .= (!$_GET["bold"])?"":"font-weight:bold;";
 $style .= (!$color || $color == "#")?"":"color:{$color};";
 $style .= (!$size || $size == "16")?"":"font-size:{$size}px;";
 $t = time();
 for($i = 1;$i<count($arr);$i++)
 {
 $content = $arr[$i];
 $content = str_replace(array("\n","\r"),"",$content);
 if ($content == "") continue;
 $content = preg_replace("!<img\s+(.*?)/>!i", "[img $1/]", $content);
 $content = str_replace(array('<', '>'), array('<', '>'), $content);
 $content = preg_replace("!\[img (.*?)/\]!i", "<img $1/>", $content);
 $content = str_replace($lang['ban'], '', $content);
 $content = ($style)?"<span style='{$style}'>{$content}</span>":$content;
 $ubbarray = array('[:ani_wink:]',
 '[:big_eyes:]',
 '[:cool:]',
 '[:cry:]',
 '[:eye_roll:]',
 '[:grin:]',
 '[:happy:]',
 '[:not_impressed:]',
 '[:smile:]',
 '[:smile_eyes:]',
 '[:stickout:]',
 '[:straight:]',
 '[:surprised:]',
 '[:unhappy:]',
 '[:wink:]');
 $content = str_replace($ubbarray, 
 array('<img src="smilies/ani_wink.gif" />',
 '<img src="smilies/big_eyes.gif" />',
 '<img src="smilies/cool.gif" />',
 '<img src="smilies/cry.gif" />',
 '<img src="smilies/eye_roll.gif" />',
 '<img src="smilies/grin.gif" />',
 '<img src="smilies/happy.gif" />',
 '<img src="smilies/not_impressed.gif" />',
 '<img src="smilies/smile.gif" />',
 '<img src="smilies/smile_eyes.gif" />',
 '<img src="smilies/stickout.gif" />',
 '<img src="smilies/straight.gif" />',
 '<img src="smilies/surprised.gif" />',
 '<img src="smilies/unhappy.gif" />',
 '<img src="smilies/wink.gif" />'), 
 $content);
 $s.= $t."|".$name.":".$content."\n";
 }
 if (!$name) die("No Name!!");
 if (!$s) die("No Content!!");
 $fp = @fopen($filename,"a+");
 if (!$fp) die("repeat");
 if (@flock($fp, LOCK_EX))
 {
 @fputs($fp,$s);
 @flock($fp, LOCK_UN);
 }
 else die("repeat");
 @fclose($fp);
 echo "OK";
}
else if (trim($action) == "read")
{
 if (get_magic_quotes_runtime()) {
 set_magic_quotes_runtime(0);
 }
 $first = $_GET["first"];
 $lastmod = intval($_GET["lastmod"]);
 $alastmod = @filemtime($filename);
 $name = file_get_contents("php://input");
 $name = str_replace("\n","",$name);
 $ip = get_ip();
 $json = array();
 $json["lastmod"] = $alastmod;
 $item = array();
 $newonline = array();
 $offline = array();

 $lines = @file($filename);
 if ($alastmod > $lastmod && !$first)
 {
 foreach($lines as $l)
 {
 $item2 = array();
 $l = str_replace(array("\n","\r"),"",$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"] = stripslashes($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("\n","\r"),"",$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"] = stripslashes($arr[1]);
 $item[] = $item2;
 }
 $item = array_reverse($item);
 }

 $s = "";
 $nt = time();
 $onlines = array();
 if($disonline)
 {
 $users = @file($datafile);
 foreach($users as $l)
 {
 $l = str_replace(array("\r","\n"),"",$l);
 if (strpos($l,"|") === false)
 {
 $s.=$l."\n";
 continue;
 }
 $arr = explode("|",$l);
 if ($nt - intval($arr[1]) < $touchs*2+1)
 {
 if (trim($name) == trim($arr[2]))
 {
 $s.= $arr[0]."|".time()."|".$name."|".get_ip()."|\n";
 }
 else $s.=$l."\n";
 $onlines [] = $arr[2];
 }
 }
 @file_put_contents($datafile,$s);
 $json["onlines"] = $onlines;
 }
 $json["lines"] = $item;
 echo array2json($json);
 if (!get_magic_quotes_runtime()) {
 set_magic_quotes_runtime(1);
 }
}
else
{
?>

安装说明:

因为这一款php+ajax实时聊天室的聊天记录是保存到PHP文件中的,所以不用导入数据库,安装自然也就方便多了,只需要将下载的文件包解压缩到可以运行PHP的根目录下即可.

源码下载:php+ajax实时聊天室

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
php中3种方法统计字符串中每种字符的个数并排序
Aug 27 PHP
关于PHPDocument 代码注释规范的总结
Jun 25 PHP
改写函数实现PHP二维/三维数组转字符串
Sep 13 PHP
ThinkPHP CURD方法之where方法详解
Jun 18 PHP
修改destoon会员公司的伪静态中的com目录的方法
Aug 21 PHP
ThinkPHP水印功能实现修复PNG透明水印并增加JPEG图片质量可调整
Nov 05 PHP
PHP扩展模块memcached长连接使用方法分析
Dec 24 PHP
thinkphp配置文件路径的实现方法
Aug 30 PHP
php实现等比例压缩图片
Jul 26 PHP
PHP的PDO连接讲解
Jan 24 PHP
PHP PDOStatement::execute讲解
Jan 31 PHP
Laravel 微信小程序后端实现用户登录的示例代码
Nov 26 PHP
php验证身份证号码正确性的函数
Jul 20 #PHP
PHP加密解密类实例代码
Jul 20 #PHP
php图片添加水印例子
Jul 20 #PHP
支付宝服务窗API接口开发php版本
Jul 20 #PHP
PHP二维数组矩形转置实例
Jul 20 #PHP
php实现登录tplink WR882N获取IP和重启的方法
Jul 20 #PHP
PHP的AES加密算法完整实例
Jul 20 #PHP
You might like
IIS+fastcgi下PHP运行超时问题的解决办法详解
2013/06/20 PHP
jQuery中setTimeout的几种使用方法小结
2013/04/07 Javascript
通过action传过来的值在option获取进行验证的方法
2013/11/14 Javascript
javascript中处理时间戳为日期格式的方法
2014/01/02 Javascript
js弹出确认是否删除对话框
2014/03/27 Javascript
node.js中watch机制详解
2014/11/17 Javascript
XML文件转化成NSData对象的方法
2015/08/12 Javascript
js中javascript:void(0) 真正含义
2020/11/05 Javascript
javascript实现密码验证
2015/11/10 Javascript
深入理解Angular2 模板语法
2016/08/07 Javascript
jQuery实现select模糊查询(反射机制)
2017/01/14 Javascript
js 获取图像缩放后的实际宽高,位置等信息
2017/03/07 Javascript
Node.js+Express+MySql实现用户登录注册功能
2017/07/10 Javascript
vue2.0 + element UI 中 el-table 数据导出Excel的方法
2018/03/02 Javascript
解析JS在获取当前月的最后一天遇到的坑
2019/08/30 Javascript
Vue实现点击当前元素以外的地方隐藏当前元素(实现思路)
2019/12/04 Javascript
ES6 proxy和reflect的使用方法与应用实例分析
2020/02/15 Javascript
JS eval代码快速解密实例解析
2020/04/23 Javascript
解决echarts echarts数据动态更新和dataZoom被重置问题
2020/07/20 Javascript
跟老齐学Python之大话题小函数(1)
2014/10/10 Python
Python编程中用close()方法关闭文件的教程
2015/05/24 Python
Python 制作糗事百科爬虫实例
2016/09/22 Python
Windows系统下多版本pip的共存问题详解
2017/10/10 Python
在pycharm中使用git版本管理以及同步github的方法
2019/01/16 Python
在Pycharm中修改文件默认打开方式的方法
2019/01/17 Python
Django自带日志 settings.py文件配置方法
2019/08/30 Python
Python xmltodict模块安装及代码实例
2020/10/05 Python
canvas探照灯效果的示例代码
2018/11/30 HTML / CSS
斯凯奇新西兰官网:SKECHERS新西兰
2018/02/22 全球购物
高尔夫球鞋、服装、手套和装备:FootJoy
2018/12/15 全球购物
说出你对remoting 和webservice的理解和应用
2014/06/08 面试题
如何客观的进行自我评价
2013/12/17 职场文书
民事赔偿协议书
2014/11/02 职场文书
会计专业求职信范文
2015/03/19 职场文书
Python实现打乒乓小游戏
2021/09/25 Python
python基础之模块的导入
2021/10/24 Python