How to manipulate txt lines in php?

0

I'm developing a chat based on document.html, but I would like to be manipulating and limiting the number of lines: follow my current code

 <?php
 $nome = $_POST['nome'];
 $mensagem = $_POST['mensagem'];
 $linha = $nome.' - '.$mensagem.'<br>';
 $arquivo = file('chatlog.htm');
 array_push($arquivo, $linha);
 file_put_contents('chatlog.htm', $arquivo);
 ?>

Doubts: My first question is how do I get my code inserted in lines? Currently the file is being written as phrases

EX like this: Joao - Ola br Jose - OI br Joao - alright? br ...
EX like you would like:
line1: Joao - Ola
line2: Jose - OI
line3: John - all right? Home ...

The second question is how do I delete everything before or after the EX: tenth line.

    
asked by anonymous 09.02.2016 / 00:56

3 answers

2

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>
    
10.02.2016 / 16:23
0

Well I would like to learn how to use these functions from what I saw was based on arrays in txt, more searching I found this script of a project in a chat that fell like a glove, because I did what I wanted only another way follows the code and the credits

link

<?php

 /**

  * Author: chris at linuxuser.at

  * Licence: MIT

  */



 $fn = "chat.txt";

 $maxlines = 20;



 $nick_maxlength = 10;



 /* Set this to a minimum wait time between posts (in sec) */

 $waittime_sec = 0;



 /* spam keywords */

 $spam[] = "cum";

 $spam[] = "dick";



 /* IP's to block */

 $blockip[] = "72.60.167.89";



 /* spam, if message IS exactly that string */

 $espam[] = "ajax";



 $msg = $_REQUEST["m"];

 $n = $_REQUEST["n"];



 if ($waittime_sec > 0) {

     $lastvisit = $_COOKIE["lachatlv"];

     setcookie("lachatlv", time());



     if ($lastvisit != "") {

         $diff = time() - $lastvisit;

         if ($diff < $waittime_sec) { die(); }

     }

 }



 if ($msg != "") {

     if (strlen($msg) < 2) { die(); }

     if (strlen($msg) > 3) {

         /* Smilies are ok */

         if (strtoupper($msg) == $msg) { die(); }

     }

     if (strlen($msg) > 150) { die(); }

     if (strlen($msg) > 15) {

         if (substr_count($msg, substr($msg, 6, 8)) > 1) { die(); }

     }



     foreach ($blockip as $a) {

         if ($_SERVER["REMOTE_ADDR"] == $a) { die(); }

     }



     $mystring = strtoupper($msg);

     foreach ($spam as $a) {

          if (strpos($mystring, strtoupper($a)) === false) {

              /* Everything Ok Here */

          } else {

              die();

          }

     }



     foreach ($espam as $a) {

         if (strtoupper($msg) == strtoupper($a)) { die(); }

     }



     $handle = fopen ($fn, 'r');

     $chattext = fread($handle, filesize($fn)); fclose($handle);



     $arr1 = explode("\n", $chattext);



     if (count($arr1) > $maxlines) {

         /* Pruning */

         $arr1 = array_reverse($arr1);

         for ($i=0; $i<$maxlines; $i++) { $arr2[$i] = $arr1[$i]; }

         $arr2 = array_reverse($arr2);

     } else {

         $arr2 = $arr1;

     }



     $chattext = implode("\n", $arr2);



     // Last spam filter: die if message has already been in the chat history

     if (substr_count($chattext, $msg) > 2) { die(); }



     $spaces = "";

     if (strlen($n) > $nick_maxlength-1) $n = substr($n, 0, $nick_maxlength-1);

     for ($i=0; $i<($nick_maxlength - strlen($n)); $i++) $spaces .= " ";



     $out = $chattext . $n . $spaces . "| " . $msg . "\n";

     $out = str_replace("\'", "'", $out);

     $out = str_replace("\\"", "\"", $out);



     $handle = fopen ($fn, 'w'); fwrite ($handle, $out); fclose($handle);

 }

? >

    
09.02.2016 / 16:21
-2

For the first question, try everything in paragraphs, as follows:

 $linha = "<p>" .$nome. " - " .$mensagem. "<p>";

For the second, you can put to delete ALL messages with a button or every X seconds, if you prefer. To do this, use fopen (and convert your file to txt):

setInterval(function(){
$desfaz = fopen("chatlog.txt","w+");
 fclose($desfaz);
}, 300000);

This will cause the file to be re-created (and delete the logs, logically) every 5 minutes.

    
09.02.2016 / 14:20