我只是在做作业,不要问我为什么不使用SQL。
这就是我的程序所做的,它有一个注册表格,生成一个包含用户名、密码和电话号码的.txt文件。生成用户信息的模式如下:$username|$phone |$password,因此您可以看到它们用|分隔,并且.txt文件中的每一个新创建都会出现在一行。在注册表中一切都很好。我现在需要做的是创建一个搜索$username和$phone的更改密码表单,我确实做到了,但在找到现有信息后,我应该从.txt文件中更改$password,我不知道如何更改,这就是我迄今为止所做的:
HTML:
<form method="POST" action="change.php">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" placeholder="Enter username" name="username" />
</div>
<div class="form-group">
<label for="telephone">Telephone:</label>
<input type="text" class="form-control" placeholder="Enter thelephone" name="phone" />
</div>
<button type="submit" class="btn btn-secondary">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();
} */
}
快速:我会检查用户名和电话,然后用行中的新密码替换旧密码(字符串,你必须不要用explode((中的数组覆盖(,然后附加到新内容中。最后,写入文件。
$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);