[英]Modify a specific string from a txt file in PHP
我只是在做功课,不要问我为什么不为此使用 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>
更改.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()中的数组覆盖)然后append 到新内容。 最后,写入文件。
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.