当前位置:Gxlcms > php框架 > 值得分享的php+ajax实时聊天室

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

时间:2021-07-01 10:21:17 帮助过:9人阅读

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

具体的效果看如下图:

关键代码:

  1. <?php
  2. header('content-type:text/html;charset=utf-8');
  3. //显示在线用户
  4. $disonline = 1;
  5. //新登陆时显示最近内容的条数(默认为30条)
  6. $leastnum = 30;
  7. //默认的房间名(默认是每天换一个文件),如果去掉d,则是每月换一个文件
  8. $room = date("Y-m-d");
  9. //房间保存路径,必须仿quot;/"结尾,可以丿quot;../",等
  10. $roomdir = "rooms/";
  11. //编码方式
  12. $charset = "UTF-8";
  13. //客户端最大显示内容条数(建议不要太大)
  14. $maxdisplay = 300;
  15. //语言包
  16. $lang = array(
  17. //聊天室描述
  18. "description"=>"聊天室.",
  19. //聊天室标题
  20. "title"=>"Welcome...!",
  21. //第一个到聊天室的欢迎
  22. "firstone"=>"<span style='font-size:16px;color:blue;'>Welcome...!</span>",
  23. //当信息有禁止内容时显示
  24. "ban" => array('法轮功', '共产党', '李洪志', 'fuck', '叼', '你妈的', '他妈的'),
  25. //关键字
  26. "keywords"=>"Welcome...!",
  27. //发言提示
  28. "hereyourwords" => "在这里发言!"
  29. );
  30. $touchs = 10;
  31. $title = $lang["title"];
  32. $earlier = 10;
  33. $description = $lang["description"];
  34. $origroom = $room;
  35. $least = ($_GET["dis"])?intval($_GET["dis"]):$leastnum;
  36. if ($_GET["room"]) $room = $_GET["room"];
  37. $room = checkfilename($room);
  38. if (!$room) $room = $origroom;
  39. $filename = $roomdir.$room.".dat.php";
  40. $datafile = $roomdir.$room.".php";
  41. if (!is_dir($roomdir)) {
  42. @mkdir($roomdir, 0777) or exit('no this dir.');
  43. }
  44. if(file_exists($filename)){
  45. if ((int)filemtime($filename) + 1800 < time()) {
  46. unlink($filename);
  47. }
  48. }
  49. if (!file_exists($filename)) @file_put_contents($filename,'<?php die();?>'."\n".time()."|".$lang["firstone"]."\n");
  50. if (!file_exists($datafile)) @file_put_contents($datafile,'<?php die();?>'."\n");
  51. $action = $_GET["action"];
  52. if (!function_exists("file_get_contents"))
  53. {
  54. function file_get_contents($path)
  55. {
  56. if (!file_exists($path)) return false;
  57. $fp=@fopen($path,"r");
  58. $all=fread($fp,filesize($path));
  59. fclose($fp);
  60. return $all;
  61. }
  62. }
  63. if (!function_exists("file_put_contents"))
  64. {
  65. function file_put_contents($path,$val)
  66. {
  67. $fp=@fopen($path,"w");
  68. fputs($fp,$val);
  69. fclose($fp);
  70. return true;
  71. }
  72. }
  73. function checkfilename($file)
  74. {
  75. if (!$file) return "";
  76. $file = trim($file);
  77. $a = substr($file,-1);
  78. $file = eregi_replace("^[.\\\/]*","",$file);
  79. $file = eregi_replace("[.\\\/]*$","",$file);
  80. $arr = array("../","./","/","\\","..\\",".\\");
  81. $file = str_replace($arr,"",$file);
  82. return $file;
  83. }
  84. function get_ip()
  85. {
  86. global $_SERVER;
  87. if ($_SERVER)
  88. {
  89. if ( $_SERVER[HTTP_X_FORWARDED_FOR] )
  90. $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  91. else if ( $_SERVER["HTTP_CLIENT_ip"] )
  92. $realip = $_SERVER["HTTP_CLIENT_ip"];
  93. else
  94. $realip = $_SERVER["REMOTE_ADDR"];
  95. }
  96. else
  97. {
  98. if ( getenv( 'HTTP_X_FORWARDED_FOR' ) )
  99. $realip = getenv( 'HTTP_X_FORWARDED_FOR' );
  100. else if ( getenv( 'HTTP_CLIENT_ip' ) )
  101. $realip = getenv( 'HTTP_CLIENT_ip' );
  102. else
  103. $realip = getenv( 'REMOTE_ADDR' );
  104. }
  105. return $realip;
  106. }
  107. function array2json($arr)
  108. {
  109. if (function_exists('json_encode')) return json_encode($arr);
  110. $keys = array_keys($arr);
  111. $isarr = true;
  112. $json = "";
  113. for($i=0;$i<count($keys);$i++)
  114. {
  115. if ($keys[$i] !== $i)
  116. {
  117. $isarr = false;
  118. break;
  119. }
  120. }
  121. $json = $space;
  122. $json.= ($isarr)?"[":"{";
  123. for($i=0;$i<count($keys);$i++)
  124. {
  125. if ($i!=0) $json.= ",";
  126. $item = $arr[$keys[$i]];
  127. $json.=($isarr)?"":$keys[$i].':';
  128. if (is_array($item))
  129. $json.=array2json($item);
  130. else if (is_string($item))
  131. $json.='"'.str_replace(array("\r","\n"),"",$item).'"';
  132. else $json.=$item;
  133. }
  134. $json.= ($isarr)?"]":"}";
  135. return $json;
  136. }
  137. if ($action == "write")
  138. {
  139. $color = $_GET['color'];
  140. if (!eregi("[0-9a-fA-F]{6}",$color) || $color == "#000000") $color = "";
  141. $color = "#".$color;
  142. $size = intval($_GET["size"]);
  143. $arr = @file("php://input");
  144. $name = str_replace(array("\n","\r"),"",$arr[0]);
  145. $ip = get_ip();
  146. if ($disonline)
  147. {
  148. $onlines = @file_get_contents($datafile);
  149. $s1 = "|{$name}|{$ip}|";
  150. if (strpos($onlines,$s1) === false)
  151. {
  152. if (strpos($onlines,"|".$name."|") === false)
  153. {
  154. $fp = @fopen($datafile,"a+");
  155. if ($fp)
  156. {
  157. if (@flock($fp, LOCK_EX))
  158. {
  159. @fputs($fp,time()."|".time().$s1."\n");
  160. @flock($fp, LOCK_UN);
  161. }
  162. @fclose($fp);
  163. }
  164. }
  165. else
  166. {
  167. echo "NAME";
  168. die();
  169. }
  170. }
  171. }
  172. $s = "";
  173. $style = "";
  174. $font = $_GET["font"];
  175. if ($font == "songti") $font = "宋体";
  176. else if ($font == "heiti") $font = "黑体";
  177. else if ($font == "kaiti") $font = "楷体_GB2312";
  178. else $font = "";
  179. $style .= (!$font)?"":"font-family:".$font.";";
  180. $style .= (!$_GET["bold"])?"":"font-weight:bold;";
  181. $style .= (!$color || $color == "#")?"":"color:{$color};";
  182. $style .= (!$size || $size == "16")?"":"font-size:{$size}px;";
  183. $t = time();
  184. for($i = 1;$i<count($arr);$i++)
  185. {
  186. $content = $arr[$i];
  187. $content = str_replace(array("\n","\r"),"",$content);
  188. if ($content == "") continue;
  189. $content = preg_replace("!<img\s+(.*?)/>!i", "[img $1/]", $content);
  190. $content = str_replace(array('<', '>'), array('<', '>'), $content);
  191. $content = preg_replace("!\[img (.*?)/\]!i", "<img $1/>", $content);
  192. $content = str_replace($lang['ban'], '', $content);
  193. $content = ($style)?"<span style='{$style}'>{$content}</span>":$content;
  194. $ubbarray = array('[:ani_wink:]',
  195. '[:big_eyes:]',
  196. '[:cool:]',
  197. '[:cry:]',
  198. '[:eye_roll:]',
  199. '[:grin:]',
  200. '[:happy:]',
  201. '[:not_impressed:]',
  202. '[:smile:]',
  203. '[:smile_eyes:]',
  204. '[:stickout:]',
  205. '[:straight:]',
  206. '[:surprised:]',
  207. '[:unhappy:]',
  208. '[:wink:]');
  209. $content = str_replace($ubbarray,
  210. array('<img src="smilies/ani_wink.gif" />',
  211. '<img src="smilies/big_eyes.gif" />',
  212. '<img src="smilies/cool.gif" />',
  213. '<img src="smilies/cry.gif" />',
  214. '<img src="smilies/eye_roll.gif" />',
  215. '<img src="smilies/grin.gif" />',
  216. '<img src="smilies/happy.gif" />',
  217. '<img src="smilies/not_impressed.gif" />',
  218. '<img src="smilies/smile.gif" />',
  219. '<img src="smilies/smile_eyes.gif" />',
  220. '<img src="smilies/stickout.gif" />',
  221. '<img src="smilies/straight.gif" />',
  222. '<img src="smilies/surprised.gif" />',
  223. '<img src="smilies/unhappy.gif" />',
  224. '<img src="smilies/wink.gif" />'),
  225. $content);
  226. $s.= $t."|".$name.":".$content."\n";
  227. }
  228. if (!$name) die("No Name!!");
  229. if (!$s) die("No Content!!");
  230. $fp = @fopen($filename,"a+");
  231. if (!$fp) die("repeat");
  232. if (@flock($fp, LOCK_EX))
  233. {
  234. @fputs($fp,$s);
  235. @flock($fp, LOCK_UN);
  236. }
  237. else die("repeat");
  238. @fclose($fp);
  239. echo "OK";
  240. }
  241. else if (trim($action) == "read")
  242. {
  243. if (get_magic_quotes_runtime()) {
  244. set_magic_quotes_runtime(0);
  245. }
  246. $first = $_GET["first"];
  247. $lastmod = intval($_GET["lastmod"]);
  248. $alastmod = @filemtime($filename);
  249. $name = file_get_contents("php://input");
  250. $name = str_replace("\n","",$name);
  251. $ip = get_ip();
  252. $json = array();
  253. $json["lastmod"] = $alastmod;
  254. $item = array();
  255. $newonline = array();
  256. $offline = array();
  257. $lines = @file($filename);
  258. if ($alastmod > $lastmod && !$first)
  259. {
  260. foreach($lines as $l)
  261. {
  262. $item2 = array();
  263. $l = str_replace(array("\n","\r"),"",$l);
  264. if (strpos($l,"|") === false) continue;
  265. $arr = explode("|",$l);
  266. $t = intval($arr[0]);
  267. if ($t > $lastmod)
  268. {
  269. $item2["time"] = date("H:i:s",$t);
  270. $item2["word"] = stripslashes($arr[1]);
  271. $item[] = $item2;
  272. }
  273. }
  274. }
  275. else if ($first)
  276. {
  277. $item = array();
  278. $total = count($lines);
  279. for($i=$total-1;$i>=$total-$least;$i--)
  280. {
  281. if ($i<=0) break;
  282. $item2 = array();
  283. $l = str_replace(array("\n","\r"),"",$lines[$i]);
  284. if (strpos($l,"|") === false) continue;
  285. $arr = explode("|",$l);
  286. $t = intval($arr[0]);
  287. $item2["time"] = (date("m-d",time()) == date("m-d",$t))?date("H:i:s",$t):date("m-d H:i",$t);
  288. $item2["word"] = stripslashes($arr[1]);
  289. $item[] = $item2;
  290. }
  291. $item = array_reverse($item);
  292. }
  293. $s = "";
  294. $nt = time();
  295. $onlines = array();
  296. if($disonline)
  297. {
  298. $users = @file($datafile);
  299. foreach($users as $l)
  300. {
  301. $l = str_replace(array("\r","\n"),"",$l);
  302. if (strpos($l,"|") === false)
  303. {
  304. $s.=$l."\n";
  305. continue;
  306. }
  307. $arr = explode("|",$l);
  308. if ($nt - intval($arr[1]) < $touchs*2+1)
  309. {
  310. if (trim($name) == trim($arr[2]))
  311. {
  312. $s.= $arr[0]."|".time()."|".$name."|".get_ip()."|\n";
  313. }
  314. else $s.=$l."\n";
  315. $onlines [] = $arr[2];
  316. }
  317. }
  318. @file_put_contents($datafile,$s);
  319. $json["onlines"] = $onlines;
  320. }
  321. $json["lines"] = $item;
  322. echo array2json($json);
  323. if (!get_magic_quotes_runtime()) {
  324. set_magic_quotes_runtime(1);
  325. }
  326. }
  327. else
  328. {
  329. ?>

安装说明:

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

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

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

人气教程排行