值得分享的php+ajax實(shí)時(shí)聊天室
來源:易賢網(wǎng) 閱讀:639 次 日期:2016-08-12 14:19:12
溫馨提示:易賢網(wǎng)小編為您整理了“值得分享的php+ajax實(shí)時(shí)聊天室”,方便廣大網(wǎng)友查閱!

非常經(jīng)典的一款php+ajax實(shí)時(shí)聊天室,其中使用PHP文件保存聊天記錄,按天劃分,PHP實(shí)現(xiàn)聊天的功能只有一個(gè)文件,整合了PHP與AJAX技術(shù),也就是說只要運(yùn)行這一個(gè)文件就可以啟動(dòng)PHP的聊天室了,關(guān)于代碼上面也是非常的簡單,但是實(shí)現(xiàn)了聊天室一般的功能,聊天時(shí)的昵稱,更改昵稱的顏色,聊天字號(hào)大小,字體,加粗,窗體的變大變小等等,如果你想搞個(gè)聊天室來玩玩,這個(gè)源碼完全可以滿足普通的需求。

具體的效果看如下圖:

名單

關(guān)鍵代碼:

<?php

header('content-type:text/html;charset=utf-8');

//顯示在線用戶

$disonline = 1;

//新登陸時(shí)顯示最近內(nèi)容的條數(shù)(默認(rèn)為30條)

$leastnum = 30;

//默認(rèn)的房間名(默認(rèn)是每天換一個(gè)文件),如果去掉d,則是每月?lián)Q一個(gè)文件

$room = date("Y-m-d");

//房間保存路徑,必須仿quot;/"結(jié)尾,可以丿quot;../",等

$roomdir = "rooms/";

//編碼方式

$charset = "UTF-8";

//客戶端最大顯示內(nèi)容條數(shù)(建議不要太大)

$maxdisplay = 300;

//語言包

$lang = array(

//聊天室描述

"description"=>"聊天室.", 

//聊天室標(biāo)題

"title"=>"Welcome...!",

//第一個(gè)到聊天室的歡迎

"firstone"=>"<span style='font-size:16px;color:blue;'>Welcome...!</span>", 

//當(dāng)信息有禁止內(nèi)容時(shí)顯示

"ban" => array('法輪功', '共產(chǎn)黨', '李洪志', 'fuck', '叼', '你媽的', '他媽的'),

//關(guān)鍵字

"keywords"=>"Welcome...!",

//發(fā)言提示

"hereyourwords" => "在這里發(fā)言!"

);

$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

{

?>

安裝說明:

因?yàn)檫@一款php+ajax實(shí)時(shí)聊天室的聊天記錄是保存到PHP文件中的,所以不用導(dǎo)入數(shù)據(jù)庫,安裝自然也就方便多了,只需要將下載的文件包解壓縮到可以運(yùn)行PHP的根目錄下即可.

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:值得分享的php+ajax實(shí)時(shí)聊天室
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)