_php example of Php+ajax real-time chat room worth sharing

Source: Internet
Author: User
Tags explode flock

A very classic Php+ajax real-time chat room, where the use of PHP file to save chat records, divided by day, PHP to implement the chat function only a file, integrated PHP and Ajax technology, that is, as long as the running of this file can start PHP chat room, It's also very simple on the code, but realized the chat room general function, chat nickname, change the nickname color, chat size, font, bold, the form of large and small, and so on, if you want to get a chat room to play, this source can fully meet the needs of ordinary.

The concrete effect looks like the following figure:

Key code:

<?php header (' Content-type:text/html;charset=utf-8 ');
Show online users $disonline = 1;
The number of items that display the most recent content when the new login (default is 30) $leastnum = 30;
Default room name (the default is to change a file every day), if you remove D, it is a monthly change of file $room = Date ("y-m-d"); The room saves the path, must imitate quot;/"the end, may in heart quot;
/", etc. $roomdir =" rooms/";
Encoding method $charset = "UTF-8";
The maximum number of client display content bars (not recommended too large) $maxdisplay = 300; Language Pack $lang = array (//Chat Room description "description" => "chat room",///chat room title "title" => "welcome...!",//First Welcome to chat room "Firstone" => " <span style= ' Font-size:16px;color:blue; ' >welcome...! </span> ",///When information has prohibited content display" ban "=> Array (' Falun Gong ', ' communist ', ' Li Hongzhi ', ' fuck ', ' diao ', ' Your Mother ', ' fucking '),//keywords" keywords "=>" We

lcome...! ",//speaking hint" hereyourwords "=>" speak here! ");
$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) Filemtim
 E ($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;
 The 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); $s 1 = "| {$name}|
 {$ip}| "; if (Strpos ($onlines, $s 1) = = False) {if Strpos ($onlines, "|"). $name. "|")
 = = False) {$fp = @fopen ($datafile, "A +"); if ($fp) {if (@flock ($FP, lock_ex)) {@fputs ($fp, Time (). "|". Time (). $s 1. "
 \ n ");
 @flock ($fp, Lock_un);
 } @fclose ($FP);
 } else {echo ' NAME ';
 Die ();
 }}} $s = "";
 $style = "";
 $font = $_get["Font"];
 if ($font = = "Songti") $font = "Song Body"; else if ($font = = "Heiti") $font= "Blackbody";
 else if ($font = = "Kaiti") $font = "italics _gb2312";
 else $font = "";
 $style. = (! $font)? "": "Font-family:". $font. ";";
 $style. = (!$_get["bold"])? "": "Font-weight:bold;";
 $style. = (! $color | | $color = "#") "": "color:{$color};";
 $style. = (! $size | | $size = = "": "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 ("!!i "," [img $1/] ", $content);
 $content = str_replace (Array (' < ', ' > '), Array (' < ', ' > '), $content); $content = Preg_replace ("!\[img" (. *?)
 /\]!i ","  ", $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 ('  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ', '  '), $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["a";
 $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) {$item 2 = array ();
 $l = Str_replace (Array ("\ n", "\ R"), "", $l); if (Strpos ($l, "|")
 = = False) continue;
 $arr = Explode ("|", $l);
 $t = intval ($arr [0]);
 if ($t > $lastmod) {$item 2["time" = Date ("H:i:s", $t);
 $item 2["word"] = stripslashes ($arr [1]);
 $item [] = $item 2;
 }} else if ($first) {$item = array ();
 $total = count ($lines); for ($i = $total-1; $i >= $total-$least; $i-) {
 if ($i <=0) break;
 $item 2 = array ();
 $l = Str_replace (Array ("\ n", "\ R"), "", $lines [$i]); if (Strpos ($l, "|")
 = = False) continue;
 $arr = Explode ("|", $l);
 $t = intval ($arr [0]);
 $item 2[' time ' = (date ("M-d", Time ()) = = Date ("m-d", $t))? Date ("H:i:s", $t):d ate ("m-d h:i", $t);
 $item 2["word"] = stripslashes ($arr [1]);
 $item [] = $item 2;
 } $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 {?>
 

Installation Instructions:

Because this php+ajax real-time chat room chat record is saved to the PHP file, so do not import the database, installation naturally more convenient, just want to download the file package to be able to run PHP root directory can be.

source Download:php+ajax Real-time chat room

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.