Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

html - How to dynamically modify a text file on a php site in real time

I'm currently displaying a txt file on my website which is constantly being modified. Is there any way to display the modifications to the text file on the page in real time so I don't need to set a page refresh timer to see changes? The full code for my site can be found here. https://pastebin.com/JauZurS7

if (isset($_GET['enSubmit']) && isset($_GET['uname']) && isset($_GET['rname'])){
echo'<meta http-equiv="refresh" content="10">';
$room=$_GET['rname']; 
$uname=$_GET['uname'];
if (!is_dir($room)) mkdir($room);
$files = scandir($room);
foreach ($files as $user){
    if ($user=='.' || $user=='..') continue;
    $handle=fopen("$room/$user",'r');
    $time = fread($handle, filesize("$room/$user"));
    fclose($handle);
    if ((time()-$time)>1) unlink("$room/$user");
}
$contents='';
$filename="$room.txt";
if (file_exists($filename)){
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);    
}
$handle = fopen("$room/$uname", "w");
fwrite($handle, time());
fclose($handle);

$files = scandir($room);
$users='';
foreach ($files as $user) if ($user!='.' && $user!='..') $users.=$user."
";

if (isset($_POST['Send'])){
    $text=$_POST['txt'];
    $contents.="$uname: $text";
    $handle = fopen("$filename", "a");
    fwrite($handle, "$uname: $text
");
    fclose($handle);
}

Currently, the chat system works by people sending text which is appended to a text file. The text file is updated but in order for users to see the changes from others they have to refresh the page. To combat this I set up a 10 second refresh timer, however the problem is that people who are typing at that time will have their work removed. I'm thinking of using filemtime to append the txt file but I'm not sure how to do that.

question from:https://stackoverflow.com/questions/65623030/how-to-dynamically-modify-a-text-file-on-a-php-site-in-real-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to reply this article.

OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...