Form save and rescue data from txt file

-2

I'm making a form that writes the data entered in a .txt file by clicking on "save data" and then rescues it and shows it on the screen by pressing the "show data" button. I can not get the data to appear. I leave the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Formulario</title>
<style type="text/css">
</style>
</head>

<body bgcolor="#FFFFFF">
<FORM method="post" name="formulario">
Nombre:<input type="text" name="nombre" id="nombre">

Apellido: <input type="text" name="apellido" id="apellido">

<br />
<input type="submit" value="Guardar">
<input type="submit" value="Ver datos">

<?php
$archivo = "alumnos.txt";//
$gestor = @fopen("datos.txt", "w");

fclose($gestor);
?>
</FORM>
</body>
</html>



<?php
$nombre="";
if (!empty($_REQUEST['nombre'])){
$nombre=$_REQUEST['nombre'];
}

$apellido="";
if (!empty($_REQUEST['apellido'])){
$apellido=$_REQUEST['apellido'];

}

//Luego sobrescribo el txt

$archivo="datos.txt";

     $file=fopen($archivo,"w");
     fwrite($file,$nombre,$apellido);
  ?>
    
asked by Juan 16.10.2018 в 21:56
source

2 answers

0

Modify your code a bit to make it work better. Although you still do not know why you really need to save it in a txt on your server when with localStorage with javascript you can do it on the client side. good nothing aki goes my solution.

<?php 
//Declaro los textos que van a usar los botones de los submits
const GUARDAR = 'Guardar';
const VER_DATOS = 'Ver datos';
$datos = [];
//Inicializo las variables que contienen los valores de los inputs a null en caso de que no se haya enviado el formulario aún
$nombre = $_POST['nombre'] ?? null;
$apellido = $_POST['apellido'] ?? null;
//Si el metodo de la solicitud es un post es decir si se envio el formulario y la operacion tiene algun valor
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['operacion'])){
  //Si la operacion es la de guardar.....
  if($_POST['operacion'] === GUARDAR){
      //Abro el archivo para escribir
      $file = @fopen("archivo.txt", "a");        
      //Guardo el arreglo codificado a json
      fwrite($file, "$nombre,$apellido".PHP_EOL);
      //Cierro el archivo
      fclose($file);
      //Si quieres limpiar el formulario despues de guardar los datos descomentarea estas 2 lineas
      //$nombre = null;
      //$apellido = null;
  } else {
      //Si la operacion es la de Cargar o ver y el archivo existe
      if(file_exists('archivo.txt')){
          //Almaceno el contenido completo del archivo en esta variable
          $content = trim(file_get_contents('archivo.txt'), PHP_EOL);
          //Obtengo todas las entradas por lineas del archivo
          $lineas = explode(PHP_EOL, $content);
          foreach($lineas as $linea){
              list($name, $last) = explode(',', $linea);
              $datos[] = ['nombre' => $name, 'apellido' => $last];
          }
      }
  }
}
//Cuerpo de la página
$body = '
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Formulario</title>
    <style type="text/css">
    </style>
    </head>

    <body bgcolor="#FFFFFF">
    <FORM method="post" name="formulario" autocomplete="off">
    Nombre:<input type="text" name="nombre" id="nombre">

    Apellido: <input type="text" name="apellido" id="apellido">

    <br /><br />
    <input type="submit" value="'.GUARDAR.'" name="operacion">
    <input type="submit" value="'.VER_DATOS.'" name="operacion">

    </FORM>';

if(!empty($datos)){
    $body .= '
        <br />
        <table border="1">
            <tr>
                <th>Nombre</th>
                <th>Apellido</th>
            </tr>
    ';
    foreach($datos as $elemento){
        $body .= '
            <tr><td>'.$elemento['nombre'].'</td><td>'.$elemento['apellido'].'</td></tr>
        ';
    }
    $body .= '</table>';
}
$body .= '
    </body>
    </html>';
//Renderizo el cuerpo de la página
echo $body;

I tried it and it works well.

    
answered by 16.10.2018 / 23:10
source
0

Once I did something like this for a client who wants to save his notes in a .txt, something very simple, not only adds the notes, but also shows them.

It works, I hope it helps you. Greetings

<?php
if(isset($_POST['add'])){
 $nombre = "";
  if (!empty($_REQUEST['name'])){
   $nombre = $_REQUEST['name'];
}

$post = "";
if (!empty($_REQUEST['post'])){
 $post = $_REQUEST['post'];
}

$archivo = "notas.txt";
$file = fopen($archivo,"a");
fwrite($file,"[".$nombre."]"."\n".$post."\n".date('d/m/Y m:s')."\n"."\n");
fclose($file);
}
?>

<form method="post" action="">
<input type="text" name="name" value="notas" placeholder="Notas"><br>
<textarea name="post" placeholder="Text"></textarea><br>
<input type="submit" name="add" value="Add">
</form>

<?php
$ar = fopen("notas.txt","r") or die("No se pudo abrir el archivo");
while (!feof($ar)){
 $linea = fgets($ar);
 $lineasalto = nl2br($linea);
 echo $lineasalto;
}
fclose($ar);
?>
    
answered by 17.10.2018 в 23:52