Home > Back-end >  Modify a specific string from a txt file in PHP
Modify a specific string from a txt file in PHP

Time:08-24

I am just doing a homework don't ask me why i don't use SQL for this.

This is what my program does, it has a registration form that generates a .txt file with the username password and phone number. The pattern that generates the user info is this: $username|$phone|$password, so you can see they are separated with a | and with every new creation in the .txt file it goes on a new line. Everything works fine in the registration form. What i need to do now is create a change password form that searches for the $username and $phone, i did manage that but after finding the existing information i should alter the $password from the .txt file and i don't know how, this is what i have done so far:

HTML:

          <form method="POST" action="change.php">
                <div >
                    <label for="username">Username:</label>
                    <input type="text"  placeholder="Enter username" name="username" />
                </div>
                <div >
                    <label for="telephone">Telephone:</label>
                    <input type="text"  placeholder="Enter thelephone" name="phone" />
                </div>
                <button type="submit" >Register</button>
            </form>

change.php:

$username = $_POST['username'];
$phone = $_POST["phone"];

$users = file_get_contents("users.txt");
$users = trim($users);
$users = explode(PHP_EOL, $users);


foreach ($users as $user) {
$user = explode("|", $user);
$password = $user[2]; // This way i managed to select the $password
$password = "newpassword";
var_dump($password); //When i click submit it shows the new password but i don't know how to change just the $password in the .txt

/* if ($username == $user[0] && $phone == $user[1]) {
    header("Location: index.php?status=userFound");
    die();
} else {
    header("Location: index.php?status=userNotFound");
    die();
} */

}

CodePudding user response:

A quickie: I would check for the username and phone and then replace old password with the new one in the line (string, that u have to NOT overwite with array from explode()) and then append to new content. In the end, write to the file.

$username = $_POST['username'];
$phone = $_POST["phone"];

$users = file_get_contents("users.txt");
$users = trim($users);
$users = explode(PHP_EOL, $users);

$new_content = '';

foreach ($users as $user) {

    $user_str = $user;
    $user = explode("|", $user);
    $password = $user[2]; // This way i managed to select the $password
    $new_password = "newpassword";

    if ($user[0] == $username && $user[1] == $phone) {
        $new_user = str_replace('|' . $password, '|' . $new_password, $user_str);
    } else {
        $new_user = $user_str;
    }

    $new_content .= $new_user . PHP_EOL;
}

file_put_contents("users.txt", $new_content);
  • Related