Create new file by clicking on the button

0

Create a text file every time you click click on the save button, and save what you type in a textarea

In other words, if I press the save button 3 times, I should create a file with this:

  

file1.txt first click

     

file2.txt second click

     

file3.txt third click, etc, etc.

I have this code:

 if(isset($_POST["txtareainst"]))
 {
         if($_POST["txtareainst"])  
         {  
             $contenido=$_POST["txtareainst"];
             $archivo='D:instruccion.txt';
             $file = fopen($archivo, 'ab') or die ();           
             fwrite ($file, $contenido.PHP_EOL);
             fclose($file);
             echo "He recibido en el archivo.php: ".$_POST["txtareainst"];
         }
         else
         {echo "He recibido un campo vacio";}
 }
    
asked by Estefani_Sanchez 21.05.2017 в 01:54
source

1 answer

1

To perform this step of creating files dynamically, one option would be to use Sessions to store the counter, and some additional validations such as the method received POST , the value of the TextArea to then write the data.

Example (index.php)

<form  method="POST">
   <textarea name="textarea"></textarea>
   <input type="submit" name="Guardar" value="Guardar">
</form>

/* PHP*/
session_start(); /* Iniciamos Sessión*/
if(!isset($_SESSION['cont'])) $_SESSION['cont']=0;
if($_SERVER['REQUEST_METHOD']=='POST'){ /* Validamos el Método*/
    if(isset($_POST['textarea'])){ /* Validamos el TextArea*/
        if(trim($_POST['textarea'])!=''){/* Validamos que no esté vacío*/
            $valor = $_POST['textarea'];
            $archivo = fopen("Archivo".$_SESSION['cont'].".txt", "w");
            $_SESSION['cont']=$_SESSION['cont']+1; /* Incrementamos el contador*/
            fwrite($archivo, $valor);
            fclose($archivo);
        }
    }
}

Update

If you want to Restart the Counter you could use a second file PHP (restart.php) to do session_destroy() , in its main file where the form would create a link where it will point to the second file PHP

<a href="reiniciar.php">Reiniciar Contador</a>

In the file reiniciar.php you would have only three lines to close the session and redirect to the file where% is form

restart.php

session_start();
session_destroy();
header('Location:index.php');
  

This example is intended to have the code in the same file PHP   If you want to have two files, it may be necessary to use Ajax

    
answered by 21.05.2017 / 02:23
source