So I've made a login page and a register page. In the register page, you type an input, and then it stores the input in a .txt file that will be used in the login page.
Problem is, the login page can only read the first line from the .txt file. So if you made 2 accounts, you can only log in from the first one (the top). The second account onwards is unusable.
Here's the register function
private function _regsave()
{
if (isset($_POST['register'])) {
$nisreg = $_POST['nisreg'];
$namareg = $_POST['namereg'];
$passwordreg = $_POST['passwordreg'];
$text = $nisreg . "," . $namareg . "," . $passwordreg . "\n";
$data = "#/config.txt";
$dirname = dirname($data);
if (!is_dir($dirname)) {
mkdir($dirname, 0755, true);
}
$fp = fopen($data, 'a ');
if (fwrite($fp, $text)) {
$this->session->set_flashdata('message', '<div role="alert">
Congratulations! Your account has been created. You can now log in.</div>');
redirect('Auth');
}
}
}
And here's the Login function :
private function _login()
{
if (isset($_POST['login'])) {
$data = file_get_contents("#/config.txt");
$contents = explode("\n", $data);
foreach ($contents as $values) {
$login = explode(",", $values);
$nis = $login[0];
$name = $login[1];
$password = $login[2];
if ($nis == $_POST['nis']) {
if ($password == $_POST['password']) {
$data = [
'nis' => $nis,
'name' => $name
];
$this->session->set_userdata($data);
redirect('User');
} else {
$this->session->set_flashdata('message', '<div role="alert">Wrong password!</div>');
redirect('Auth');
}
} else {
$this->session->set_flashdata('message', '<div role="alert">Account is not registered!</div>');
redirect('Auth');
}
}
}
}
Everytime I tried to log in using the second account, it always said that the account is not registered, even though the .txt file has all the data.
Where did I go wrong?
CodePudding user response:
Your else statement (Account is not registered) is true because $nis is not equal to $_POST['nis'] for the first iteration of txt file.
Move else condition (Account is not registered) out of foreach loop.
if (isset($_POST['login'])) {
$data = file_get_contents("#/config.txt");
$contents = explode("\n", $data);
foreach ($contents as $values) {
$login = explode(",", $values);
$nis = $login[0];
$name = $login[1];
$password = $login[2];
if ($nis == $_POST['nis']) {
if ($password == $_POST['password']) {
$data = [
'nis' => $nis,
'name' => $name
];
$this->session->set_userdata($data);
redirect('User');
} else {
$this->session->set_flashdata('message', '<div role="alert">Wrong password!</div>');
redirect('Auth');
}
}
}
$this->session->set_flashdata('message', '<div role="alert">Account is not registered!</div>');
redirect('Auth');