Generate PHP system logs

Asked

Viewed 1,477 times

1

I need to generate a text document of type .txt containing information on changes made to a system web. This information is about user activities such as registration, registration changes, registration deletions and others. How this can be done, considering that the system in question is being implemented with PHP language?
I thought about using the Observer standard, but I’m not sure if it’s the best option. Is there any design pattern or framework specific to that purpose?

1 answer

3

I don’t know any framework, but it’s quite simple to do. I created the below example function using the fopen. In the function I put the files separated by date. In each line of the file has the record of the hours when the logs occurred.

function logs($texto){

        $hora = date("H:i:s"); // pega a hora
        $data = date("d-m-Y"); // pega o dia
        /*

            o "a+" abaixo significa:
            - Abre o arquivo para leitura e gravação; 
            - coloca o ponteiro no fim do arquivo. 
            - Se o arquivo não existir, tentar criá-lo.

        */
        $log = fopen("log/".$data.".txt", "a+");

        $escreve = fwrite($log, $hora." - ".$texto);// Escreve

        fclose($log); // Fecha o arquivo

    }

When something happens in the system, a register change for example, you send this information using the function logs previously created. Thus:

function alterarCadatro($nome, $email, $senha){

    ... mysqli_query...
    /*
        depois que finalizou a alteração do cadastro,
        envia a informação para a função logs
    */
    if($alterou){

        require("logs.php");
        $texto = $nome." alterou o cadastro nos campos: ".$email.",".$senha;
        logs($texto);

    }

    ...
}

Then just create your patterns, for example:

hora - tipo - local - quem

Would look like this:

00:25:05 - alteração - cadastro - Andrei

Note: This is just one example, as quoted by @Inkeliz, is necessary for you to make filters, satinize and/or create the right ones security to the code.

  • Just so you know, this would be vulnerable to Log Injection, if the $nome were biscoito alterou o cadastro nos campos: bolacha \n00:00:00 - inkeliz would add two records to the log, one improperly. Assuming it is divided by a line break each record and that the attacker knows the pattern used, either way it is something easy to mitigate, better does not bring luck to chance.

  • @Inkeliz yes.. This is just an example. I don’t think I should satinize or filter the strings to show a path. Or I should?

Browser other questions tagged

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