Save textarea content as text file

Asked

Viewed 1,345 times

0

I need to make a code that when entering what is requested in textarea and push the button submit, save the content inserted in textarea in a .txt (with line break. For example: If someone has already given Submit before and saved, do not delete what is already saved, just break a line and add the recent).

And another button Participating? pull the .txt except the contents for 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);
?>

2 answers

0

The save.php code shows this error: "This page is not working dominio.com is unable to respond to 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");
?>
  • If possible post as comment next time. It will improve and I will know if there is any other doubt. The error in this code is that a key is missing } before the ?>. By removing the comments you’ve probably removed this character.

0


First let’s go to mistakes.

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

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

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

The third error is in the button "Participating?", how he is inside the form and is set as submit, therefore, it has the function of sending the contents of the textarea to the url /salvar.php

Now, let’s go the solutions.

One of the ways to add new information to the archive is, as I explained earlier, to use the mode to+ with the function fopen.

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

Fix the button problem "Participating?", you also have two options:

  1. Create a button with the type:button and with the event click, you call a request with the XMLHttpRequest

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


How to do

I hope you can read the comments from the files very carefully. My intention is that this code can assist you in understanding the solution. I hope, too, that you read the links I left at the end to know more in depth 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");
}

php.

There are 3 simple ways to capture the contents of a file. I will post all three, but I will leave two of them I will just quote. I will leave the link so you can read more about them. I hope you can read the documentation 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:

Browser other questions tagged

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