Server-Sent Events+Ajax+PHPで簡易的なチャットを製作しています。
クライアント側でユーザーが投稿した内容がJSONファイルに書き込まれ、サーバー側でファイルの更新を監視して、更新されたら最新のデータだけクライアント側に渡す、という仕組みにしたいのですが、方法が思いつきません。
・今回解決したいこと
全部のデータではなく、最新のデータだけ取ってくるようにしたい
ご提示よろしくお願いいたします。
【ユーザーが書き込んだ内容をログファイルに書き込むPHP】
php
1<?php 2 3if($_SERVER["REQUEST_METHOD"] == "POST"){ 4mb_language("uni"); 5mb_internal_encoding("utf-8"); //内部文字コードを変更 6mb_http_input("auto"); 7mb_http_output("utf-8"); 8 9date_default_timezone_set('Asia/Tokyo'); 10 11$Penname = htmlspecialchars($_POST["Penname"]); 12$Charid = htmlspecialchars($_POST["Charid"]); 13$Charname = htmlspecialchars($_POST["Char"]); 14$Serif = htmlspecialchars($_POST["Serif"]); 15$Serif = str_replace(array('\r\n','\r','\n'), '\n', $Serif); 16$Date = date("Y/m/d H:i:s"); 17$IPaddress = $_SERVER["REMOTE_ADDR"]; 18$Hostname = gethostbyname($IPaddress); 19 20$json = file_get_contents('log/chatlog.json'); 21$records = json_decode($json, true); 22$Num = count($records); 23$Num = Num+1; 24 25$records[] = [ 26 'num' => $Num, 27 'date' => $Date, 28 'penname' => $Penname, 29 'charid' => $Charid, 30 'charname' => $Charname, 31 'serif' => $Serif, 32 'ipaddress' => $IPaddress, 33 'hostname' => $Hostname, 34]; 35 36$out_json = json_encode($records); 37 38$result = file_put_contents("log/chatlog.json", $out_json, LOCK_EX); 39} 40?>
【ログファイルの更新をチェックして最新データをクライアントに渡すPHP】
php
1<?php 2header('Content-Type: text/event-stream'); 3header('Cache-Control: no-store'); 4 5$json = file_get_contents('log/chatlog.json'); 6$data = $json; 7$temp = $data; 8 9 echo "retry: 3000\n"; 10 11 echo "id: $n\n"; 12 13 echo "event: message\n"; 14 15 printf("data: %s\n\n", $data); 16 17 echo "\n\n"; 18 19while ($temp != $data) { 20 $temp = $data; 21 ob_end_flush(); 22 flush(); 23 session_write_close(); 24 sleep(1); 25} 26?>
あなたの回答
tips
プレビュー