To insert into rows instead of using file_put_contents
use fwrite
(or fput
) and you will need to use PHP_EOL
for line breaks.
Note we recommend converting the message into html entities to prevent XSS attacks for example, for this use htmlspecialchars
.
An example to write would be:
<?php
$nome = htmlspecialchars($_POST['nome']);
$mensagem = htmlspecialchars($_POST['mensagem']);
$linha = $nome . ' - ' . $mensagem . '<br>' . PHP_EOL;
$handle = fopen('chatlog.html', 'a'); //O 'a' põe o ponteiro no final, assim a grava no final do arquivo
fwrite($handle, $linha);
fclose($handle);
I noticed that you are writing everything to a .html
that means that maybe the reading is done directly in the HTML, maybe an iframe or ajax that gets reloaded from chatlog.html
, this works, but the bigger the file the more time-consuming response page.
Note: The following steps are optional and do not have the problem, consider as a hint only, being totally optional , this process is preferred to work with Ajax or something similar and DOM manipulation by javascript.
One way the file can be using fopen
, feof
, and fgets
( fgets
reads line other than fread
that reads by size), you will need $_SESSION
or normal cookies .
The php read file should look something like (from a name like chatreader.php):
<?php
session_start();
//Verifica a última linha que o usuário leu
if (empty($_SESSION['currentLine'])) {
//Se é a primeira vez que o usuário acessa então a leitura começa do '0'.
$_SESSION['currentLine'] = 0;
}
$current = $_SESSION['currentLine'];
$i = 0;
$handle = fopen('chatlog.html', 'r');
while (false === foef($handle)) {
++$i; //Soma para contar as linhas
//Se $i for maior que $current então significa que a linha não foi lida
if ($i > $current) {
echo fgets($handle);
}
}
$_SESSION['currentLine'] = $i; //Grava a ultima posição de leitura
The javascript would look something like:
<div id="conversa"></div>
<script type="text/javascript">
function xhr() {
var xmlhttp = false;
if (XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if(ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee){}
}
}
return xmlhttp;
}
function chatReader(target) {
var x = xhr();
if (x === false) {
return;
}
x.open("GET", "chatreader.php?_=" + (new Date().getTime()), true);
x.onreadystatechange = function()
{
if (x.readyState === 4){
if (x.status === 200) {
var nd = document.createElement("div");
nd.innerHTML = x.responseText;
target.appendChild(nd);
} else {
console.log("Erro no servidor", x.status);
}
setTimeout(function() {
chatReader(target);
}, 1000);
}
};
x.send(null);
}
window.onload = function() {
var conversa = document.getElementById("conversa");
if (conversa) {
chatReader(conversa);
}
};
</script>