ajax php 聊天室实例代码(2)
- 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)
- {
- $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;
- }
- function keeponline()
- {
- global $disonline,$datafile;
- if (!$disonline) return;
- $name = $_post['name'];
- $ip = get_ip();
- $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();
- }
- }
- }
- if ($action == "write")
- {
- $color = $_post["color"];
- if (!eregi("[0-9a-fa-f]{6}",$color) || $color == "#000000") $color = "";
- $color = "#".$color;
- $size = intval($_post["size"]);
- $name = htmlspecialchars(str_replace(array("n","r"),"",$_post['name']));
- if (!$name) die("no name!!");
- $ip = get_ip();
- keeponline();
-
- $s = "";
- $style = "";
- $font = $_post["font"];
- if ($font == "songti") $font = "宋体";
- else if ($font == "heiti") $font = "黑体";
- else if ($font == "kaiti") $font = "楷体_gb2312";
- else $font = "";
- $style .= (!$font)?"":"font-family:".$font.";";
- $style .= (!$_post["bold"])?"":"font-weight:bold;";
- $style .= (!$color || $color == "#")?"":"color:{$color};";
- $style .= (!$size || $size == "16")?"":"font-size:{$size}px;";
- $t = time();
- $arr = explode("n",$_post['content']);
- if (count($arr) > 20) die('error');
- for($i = 0;$i<count($arr);$i++)
- {
- $content = $arr[$i];
- $content = trim($content);
- $content = str_replace(array("n","r"),"",$content);
- if (!$content) continue;
- $content = htmlspecialchars($content);
- $content = preg_replace("~[img](http://[a-za-z0-9.-_+%?]*)[/img]~i", "<img src='$1' />", $content);
- $content = ($style)?"<span style='{$style}'>{$content}</span>":$content;
- $s.= $t."|".$name.":".$content."n";
- }
|