php 一个简单的推送实例
<?php
set_time_limit(9990);
header('cache-control: private');
header('Content-Type: text/html; charset=utf-8');
$file="chat.txt";
$action=isset($_GET['action'])?trim($_GET['action']):'';
switch ($action){
case "say":
_say();
break;
case "chat":
_chat();
break;
default:
_main();
break;
}
//------------------------------------------------*
function _main(){
echo '<iframe src="?action=chat" height="300" width="100%"></iframe>';
echo '<form method="post" id="f1" target="say" action="?action=say"><input type="text" name="wd"><input type="submit" value="say"></form>';
echo '<iframe name="say" style="display:none"></iframe>';
}
//------------------------------------------------*
function _say(){
global $file;
$wd = trim($_POST['wd']);
if(file_exists($file)){
$htm=file_get_contents($file).$wd.chr(10);
}else{
$htm=$wd.chr(10);
}
file_put_contents($file,$htm,LOCK_EX);
clearstatcache();
}
//------------------------------------------------*
function _chat(){
global $file;
if(!file_exists($file)){
file_put_contents($file,'',LOCK_EX);
}
//这一行是为了IE的b
echo str_repeat(' ', 256);
ob_flush();
flush();
$total = count(file($file));
$i = $total - 1;
while(true){
$N=count(file($file));
if($N!=$total){
$total = $N;
$HTM=file($file);
echo '<div>',htmlspecialchars(end($HTM)),'</div>';
ob_flush();
flush();
}else{
usleep(1500);
}
}
}
?>