Skip to content
Advertisement

Php Reload When Document Is Changed

This is my php code, and i am trying to create a chat

<!DOCTYPE html>
<html>
<body>
<html>
<?php
session_start();
$userinput = $_GET["name"];
if (empty($userinput)){

} else {
    $myfile = fopen("chat.txt", "a");
    fwrite($myfile, $userinput);
    fwrite($myfile, "<br>
");
}

$chatfile = fopen("chat.txt", "r");
echo fread($chatfile,filesize("chat.txt"));
echo $chatfile;
?> 

</body>
</html>

<form method="get" id="myForm" action="">
<input type="text" name="name"
placeholder="type in your comment" autofocus>
<input type="submit">
</form>

<script>
</script>
</body>
</html>

I know that php isn’t the way to go, but I want to have some fun, and it seems to be working out. Also, I want to ask how do you let the chat let real time. I created a document called chat.txt and maybe i can detect when it is changed, and then reload. There are 2 problems to this method. 1. after each reload the message you previously typed is typed again 2.I don’t know how to detect change, and have not found any way to do this does anyone have solutions to this? (other methods would be fine) P.S. I’m horrible at php

Advertisement

Answer

PHP is a weird way to do this. To be honest, the only way I can see a “live” chat in PHP is by refreshing constantly, and even then, the user won’t be able to type. Something like this is difficult in PHP because PHP really just generates a page for you to view and it’s done. It would be much easier for you to do this with javascript. You could make the JS look into the text file every x amount of seconds and if it detects a change, then make the page refresh, or even better, update the chat’s HTML. It wouldn’t be too hard:

Read the contents of a text file every 15 seconds

You’d just need to find a way, likely in javascript, to write something to file when you press a button. That way, the other client can get your messages and you won’t need to refresh the page every time you want to send a message. Of course, this would only work with text files on local machines.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement