It was supposed to be a simple login, but only recognizes one password. Why? In password.txt it says:
moin
britta
pialo1217
in master-pwd.txt:
paul1210
But the script accepts only britta. However, with the others I just do not get any feedback. Does anyone have an idea what the problem is? I am an absolute beginner. Please do not overwhelm me directly. Here my Script:
<?php
$seiteninhalt = "";
$eingabe = $_POST["passwort"];
$seiteninhalt .= $eingabe;
$filename = file("passwort.txt");
for($i=0;$i < count($filename); $i ){
//echo $filename[$i];
if ($filename[$i] == $eingabe){
echo "Korrekte Eingabe!"; //Successfull --> normal login
}
}
$filename = file("master-pwd.txt");
for($i=0;$i < count($filename); $i ){
//echo $filename[$i];
if ($filename[$i] == $eingabe){
echo "Korrekte Eingabe! Voller zugriff!"; //Successfull --> Master login
}
}
//echo $seiteninhalt;
?>
CodePudding user response:
From file()
documentation:
Each element of the array corresponds to a line in the file, with the newline still attached.
You are probably comparing "moin" to "moin\n" or "moin\r\n". You can use trim()
or rtrim()
to get rid of those newline-characters. Or you can use file(..., FILE_IGNORE_NEW_LINES)
as suggested in the docs.
CodePudding user response:
As Roman mentioned in his answer, the reason this isn't working is because file
adds newlines to the end of each element in the array. You could put this code into a function to simplify your code:
<?php
function check_password($filename, $password)
{
$passwords = file($filename, FILE_IGNORE_NEW_LINES);
if (in_array($password, $passwords))
return true;
return false;
}
$password_to_check = 'moin';
if (check_password('master-pwd.txt', $password_to_check)) {
echo 'Master login!';
} else if (check_password('passwort.txt', $password_to_check)) {
echo 'Normal login!';
} else {
echo 'Password failed!';
}
CodePudding user response:
I think your problem might be that you are not closing access to the previous file, instead try this (I do not know if it will work as I am using very old version of PHP)
<?php
$seiteninhalt = "";
$eingabe = $_POST["passwort"];
$seiteninhalt .= $eingabe;
$filename = fopen("passwort.txt");
for($i=0;$i < count($filename); $i ){
//echo $filename[$i];
if ($filename[$i] == $eingabe){
echo "Korrekte Eingabe!"; //Successfull --> normal login
}
}
fclose($filename);
$filename = fopen("master-pwd.txt");
for($i=0;$i < count($filename); $i ){
//echo $filename[$i];
if ($filename[$i] == $eingabe){
echo "Korrekte Eingabe! Voller zugriff!"; //Successfull --> Master login
}
}
//echo $seiteninhalt;
fclose($filename);
?>