ajax php 聊天室实例代码(3)
- 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("n","",$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("n",$s);
-
- 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"] = 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("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"] = 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("r","n"),"",$l);
- if (strpos($l,"|") === false)
- {
- $s.=$l."n";
- continue;
- }
- $arr = explode("|",$l);
- if ($nt - intval($arr[1]) < $touchs*3)
- {
- if (trim($name) == trim($arr[2]))
- {
- $s.= $arr[0]."|".time()."|".$name."|".get_ip()."|n";
- }
- else $s.=$l."n";
- $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("r","n"),"",$l);
- if (strpos($l,"|") === false)
- {
- $s.=$l."n";
- continue;
- }
- $arr = explode("|",$l);
- if (trim($name) == trim($arr[2])) continue;
- else $s.=$l."n";
- }
- @file_put_contents($datafile,$s);
- echo "ok";
- }
- die();
- }
- else
- {
- ?>
|