How to manipulate txt lines in php?

Asked

Viewed 772 times

0

Well I am developing a chat based on document.html, however I would like to be manipulating and limiting the number of lines: follows 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 to get my code inserted in lines? Currently the file is being written as sentences

EX like this: Joao - Ola br Jose - OI br Joao - all right? br...
EX HOW WOULD YOU LIKE:
linha1: Joao - Ola
Inha2: Jose - OI
line3: Joao - all right?
...

The second question is how can I delete everything before or after the EX:.

  • 1

    Why not save as txt, since you treat as text file?

  • Another thing, add one \n right next to the <br>, so I think it’s enough to save line by line.

  • I changed to txt but the n is leaving in the imprint of the code

  • Change to "<br>\n". Recalling that the <br> is html tag, unless you open the file in the browser, it will be ignored.

  • continues to write n on print and txt is also not bouncing line in txt file

  • Well I created this mini tutorial many years ago, it talks how to transform Database with TXT Maybe it’ll help you do what you want.

  • Would saving with PHP_EOL help? PHP_EOL skips a line while writing to the file.

Show 2 more comments

3 answers

2

To insert into rows instead of using file_put_contents use fwrite (or fput) and it will be necessary to use PHP_EOL for line breaks.

Note it is recommended to convert the message into html entities to avoid attacks XSS for example, for this use htmlspecialchars.

An example for recording 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 you’re recording everything into one .html this means that maybe the reading is done directly in HTML, maybe an iframe or ajax that keeps doing Reload chatlog.html, this works, but the bigger the file the more time-consuming the page reply.

Note: the following steps are optional and do not have to do with the problem, consider as a tip only, being totally optional, this process described is preferred to work with Ajax or something similar and DOM manipulation by javascript.

A way the file can be using fopen, feof and fgets (fgets reads line to line different from fread which reads by size), will be required $_SESSION or normal cookies.

The php reading file should be 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

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>

0

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

https://www.metachris.com/projects/most-simple-ajax-chat-ever/

<?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);

 }

?>

-2

For the first question, try to put 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. For 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 recreated (and delete the records, of course) every 5 minutes.

  • type, the idea is even good however,I would like to be keeping a history of 30 lines of the last talk, eutou researching about count the number of jokers and delete from there the idea of why the <p> will be quite utll

  • 2

    setInterval in PHP? -1

  • 1

    Not counting the idea of deleting every 5 minutes, which was not asked in question -1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.