How to delete content from TXT file using PHP?

Asked

Viewed 463 times

-4

I am doing a php web project to monitor the network assets in my work I have a file named 'log.txt' at the root of my project which is fed with log information with date, time, ip etc. Line by line. Following example:

function functionLog($vSetor, $vIp, $vTaxa, $vPorta) {
    $fp = fopen("log.txt", "a");
    $dataLog = date("d/m/Y");
    date_default_timezone_set('America/Belem');
    $horaLog = date("H:i:s");
    fwrite($fp, $dataLog . ' ' . $horaLog . ' ' . $vSetor . ' ' . $vIp . ' ' . $vTaxa . 'ms' . ' ' . $vPorta . "\r\n");
    fclose($fp);
}
?>

But there comes a time when this file is very full of log information and need to empty with just one click

My question is: how can I call a function inside an html button for the file to be reset, that is, to delete all lines of the file 'log.txt'

  • If you open the file in mode w, the entire contents of the file will be overwritten, so it is not better within the function functionLog you check the file size and if it is larger than the desired limit it open the file as w?

  • The number of lines is unlimited. No matter how many lines appear in log And this function was the example I used to show how the txt file is created

  • You can call a page via ajax. On this page you delete the file and create a blank to receive the new information... If interested, I can formulate a response.

  • What I wanted to learn was this: https://stackoverflow.com/questions/20738329/how-to-call-a-php-function-the-click-of-a-button Now I know how to do SOLVED

1 answer

0

You have another alternative.

You could invoke the function using a form button.

And for him to look cool, he could style with css.

For example:

HTML form

<form action="/urlaqui" method="post">
    <button type="submit" name="botao">Invocar Função</button>
</form>

Invoke PHP function after clicking the button

<?php
    // Verifica se o botão foi clicado
    if( isset($_POST['botao']) ){
       // Se o botão existe, executa a função
       executeEstaFuncao();
    }

Styling button with CSS

form button{
    background-color:#ccc;
    border:1px solid #444;
    color:#666;
    cursor:pointer;
    font-size:1.1em;
}

Browser other questions tagged

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