Save textarea content as text file

1

I need to make a code that when inserting what is requested in the textarea and pressing the submit button, save the content entered in the textarea to a .txt (with a line break. already gave submit before and saved, do not delete what is already saved, just break a line and add the recent).

And another button Invoking? pulls from .txt save content to a div or a textarea (which will only be visible after pressing this button).

My code (index.php):

<form action="salvar.php" method="post">
   <center>
   <center>
   <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="redyellow">{Sorteador Skins}</font></h2>
   <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="purpleyellow">[Boa Sorte]</font></h2>
   <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="purple">(By: PumP)</font></h2>
   </center>               
   <textarea required name="ccs" id="ccs" placeholder="Insira seu nick :)" type="text" class="form-control" style="max-width: 800px; min-width: 800px; min-height: 200px; max-height: 200px; text-align: center; resize: none; color: red; background-color: #2b323d"></textarea>
   <br>
   <br>
   <center>
   <input type="submit" id="enviar" class="btn btn-danger" value="Cadastrar">
   <br>
   <br>
   <input type="submit" id="participantes" class="btn btn-sucess" value="Participando?">
</form>

save.php:

<?php
$txt = $_POST['ccs'];
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile, $ess);
fclose($myfile);
?>
    
asked by anonymous 22.12.2017 / 00:27

2 answers

0

First of all let's make mistakes.

The first is in the way you are opening the file. According to the PHP documentation, w is only used for file creation.

In your case, the correct mode is a + . This mode will allow you to open the file for writing and reading.

The second is in the name of the variable $ess , it does not exist. The correct one would be $txt

The third error is in the " Participating? " button, since it is inside form and is set to submit , so it has the function to send textarea content % for url /salvar.php

Now, let's go to the solutions.

One way to add new information to the file is, as I explained earlier, to use a + mode with the fopen function.

Another way is to use the file_put_contents function. This function will allow you to create a file or add new information to it.

When correcting the problem of the " Attending?" button, you also have two options:

  • Create a button with type:button and with click event, you call a request with XMLHttpRequest

  • Create a anchor that can take you to url /ler_arquivo.php , for example.

  • How to do

    I hope you can read the comments of the files very carefully. It is my intention that this code can assist you in understanding the solution. I hope you also read the links I left at the end to get to know more about it and choose the best option for your code.

    index.html

    <form action="salvar.php" method="post">
       <center>
       <center>
       <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="redyellow">{Sorteador Skins}</font></h2>
       <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="purpleyellow">[Boa Sorte]</font></h2>
       <br><h2 style="font: Ventana; text-shadow: 0 0 0.1em gray; color:gray;"><font face="Candara"><font color="purple">(By: PumP)</font></h2>
       </center>               
       <textarea required name="ccs" id="ccs" placeholder="Insira seu nick :)" type="text" class="form-control" style="max-width: 800px; min-width: 800px; min-height: 200px; max-height: 200px; text-align: center; resize: none; color: red; background-color: #2b323d"></textarea>
       <br>
       <br>
       <center>
       <input type="submit" id="enviar" class="btn btn-danger" value="Cadastrar">
       <br>
       <br>
       <input type="button" id="participantes" class="btn btn-sucess" value="Participando?">
    </form>
    
    
    <script>
        var participantes = document.querySelector("#participantes");
        var textarea = document.querySelector("#ccs");
    
        participantes.addEventListener("click", function() {
    
            /* Cria o objeto responsável pela requisição */
            var req = new XMLHttpRequest();
    
            /* 
             * Adiciona um evento para capturar os dados quando a
             * requisição for finalizada e joga-las no textarea
             */
            req.addEventListener("loadend", function(result) {
                textarea.value = result.target.response;
            });
    
            /* Abre a conexão com o servidor */
            req.open("GET", "capturar_arquivo.php");
    
            /* Envia o pedido */
            req.send();
    
        });
    </script>
    

    save.php

    <?php
    
    $filename = "arquivo.txt";
    
    /*
     * Verifica se o conteúdo da textarea 'ccs' foi enviado
     * Essa condição irá evitar erros
     */
    if (isset($_POST["ccs"])) {
    
        /* Captura o conteúdo enviado */
        $ccs = $_POST["ccs"];
    
        /*
         * Abre o arquivo com o modo a+
         * Esse modo permite abrir o arquivo
         * tanto para o modo de leitura, quanto
         * para o modo de escrita, além de colocar
         * o ponteiro no final do arquivo.
         */
        $file = fopen($filename, "a+");
    
        /*
         * Escreve o conteúdo enviado e adiciona
         * uma quebra de linha no arquivo.
         */
        fwrite($file, $ccs);
        fwrite($file, PHP_EOL);
    
        /**
         * Fecha o arquivo
         */
        fclose($file);
    
        /**
         * Caso você opte pela função 'file_put_contents',
         * estou deixando o link da documentação para você
         * dar uma estudada.
         */
    
        /**
         * Volta para a página index.html
         */
        header("Location: index.html");
    }
    

    capture_file.php

      

    There are 3 simple ways to capture the contents of a file.   I'll post all three, but I'll leave two of them, I'll just quote. I'll leave the link so you can read more about them.   I hope you can read the documentation that I will leave   to be able to choose better.

    <?php
    
    $filename = "arquivo.txt";
    
    /* ************************************* */
    /* Forma 1                               */
    /* ************************************* */
    
    /**
     * Arquivo o arquivo no modo somente leitura
     */
    $file = fopen($filename, "r");
    
    /* Variável onde ficará o conteúdo do arquivo */
    $content = "";
    
    /**
     * "Divide" o arquivo em várias partes de 1024 bytes
     * e depois percorre todas elas, juntando-as.
     */
    while (($line = fread($file, 1024)) != false) {
        $content .= $line;
    }
    
    
    /* ************************************* */
    /* Forma 2 - Irei deixar comentada       */
    /* ************************************* */
    // Aqui você pode utilizar a função "file_get_contents"
    
    
    /* ************************************* */
    /* Forma 3 - Irei deixar comentada       */
    /* ************************************* */
    // Aqui você poderá utilizar a função "file" e "implode"
    
    
    /* Imprime o conteúdo na tela */
    echo $content;
    

    Links:

    22.12.2017 / 02:41
    0

    The save.php code displays this error: "This page is not working domain.com is unable to meet this request at this time. HTTP ERROR 500 "

    <?php
    $filename = "arquivo.txt";
    
    
    if (isset($_POST["ccs"])) {
    
    
        $ccs = $_POST["ccs"];
    
    
        $file = fopen($filename, "a+");
    
    
        fwrite($file, $ccs);
        fwrite($file, PHP_EOL);
    
    
        fclose($file);
    
    
        header("Location: index.php");
    ?>
    
        
    22.12.2017 / 13:16