Home > Enterprise >  How could I save on a file .txt with php?
How could I save on a file .txt with php?

Time:04-17

<?php
 
 $fp = fopen("users.txt", "w");
if(!$fp) die ("Errore nella creazione dell'utente");
$fp=fwrite($email $password);
fclose($fp);

 $name="";
 $surname="";
 $email="";
 $password="";
 $nazionalita="";
 $telefono="";
 $errors= array();
 
 if($_SERVER["REQUEST_METHOD"]=="POST"){
     $name = htmlspecialchars($_POST["name"]);
     $surname = htmlspecialchars($_POST["surname"]);
     $email = htmlspecialchars($_POST["email"]);
     $password = htmlspecialchars($_POST["password"]);
     $nazionalita = htmlspecialchars($_POST["nazionalita"]);
     $telefono = = htmlspecialchars($_POST["nazionalita"]);
  }
     
 
     if(empty($name)) {
       $errors[] = "Name is required!";
   }
 
   if(empty($surname)) {
       $errors[] = "Surname is required!";
   }
 
   if(empty($email)) {
       $errors[] = "Email is required!";
   }

   if(empty($password)) {
    $errors[] = "Password is required!";
}
         
 header("location: index.php");
?>

But of course, this doesn't work.

  1. How can I save to a specific location with PHP? Then I'll have to do an explode which will only get my email and password. on the login.php page.

Thank you.

CodePudding user response:

I'm not going to fix your code for you, but give you three tips:

  1. Think like a computer. The computer is going to run your program one statement at a time, in the order you've written them; so if you have a line that writes a variable to a file, it needs to come after the line where you've put a value into that variable. It is also going to do exactly what you ask it, not guess what you meant, and not let you get away with typos; read your code back carefully.
  2. Make use of the PHP manual. If you type in https://php.net/ followed by the name of a built-in function, like https://php.net/fwrite, you will get a page that explains what the input and output of that function is. Often, there are examples which show various ways of using the function, which you can use as inspiration for how to write your own code.
  3. Turn on the display_errors setting, or learn where your log file is. Most of the mistakes in the code you show will result in errors or warnings, telling you exactly which line you need to look at. Read the messages carefully, and they'll often point out exactly what you've done wrong.

CodePudding user response:

If you want to write to the file you could do $fpw = fwrite($fp,$email.' : '.$password);

CodePudding user response:

you should pass the $fp to fwrite() method as follow

$fp = fopen('user.txt', 'w ') or die('Unable to open file!');
$fp=fwrite($fp, $email.'~'.$password.'\n'); // make sure to choose whatever seperator suits your need and be careful when choosing it
fclose($fp);
  •  Tags:  
  • php
  • Related