I have been trying to solve . this problem for days but I am at a loss of what went wrong.
Basic:
I have created a basic authentication page. All the username and passwords (MD5) are stored in a .txt file. Included in the php is an option to allow me to add users (username and password).
After I have added a username and the password, I couldn't login. I am absolutely sure that both the login and passwords are the same. After much debugging, I found out that i get 2 different MD5's for the same password.
e.g. for lyc -> efa664720fac0075674862b40d490830 & d41d8cd98f00b204e9800998ecf8427e
Attached below is my code, please kindly advise:
Code: Select all
<?php
$password_file="/var/www/pwd/pwd.txt";
function check_pass($login,$password){
global $password_file;
global $match;
global $name;
if(!$fh=fopen($password_file,"r")){
die("<p>Could Not Open Password File");
}
$match=0;
$name=0;
$password=md5($password);
while(!feof($fh)){
$line=fgets($fh,4096);
$user_pass=explode(":",$line);
if($user_passї0]==$login){
echo $login;
echo $password;
echo $user_passї0];
echo $user_passї1];
if(rtrim($user_passї1])==$password){
$match=1;
break;
}
}
}
if($match){
return 1;
} else {
return 0;
}
fclose($fh);
}
function print_login_form($login){
?>
<p>Please Login In:
<form action=authentication.php method=post>
<p>Login: <input type="text" name="login" value="<?=$login?>">
<br>Password: <input type="password" name="password">
<br><input type="submit" name="checkpass" value="Login!">
</form>
<?php
}
function print_add_form(){
?>
<p> Add New User:
<form action=authentication.php method=post>
<p>Login:<input type="text" name="adduser">
<br>Password:<input type="password" name="addpass">
<br><input type="submit" name="add" value="Add User!">
</form>
<?php
}
function add_user($adduser,$addpass){
global $password_file;
if(!$fh=fopen($password_file,"a+")){
die("<p>Could Not Open Password File");
}
rewind($fh);
while(!feof($fh)){
$line=fgets($fh,4096);
$user_pass=explode(":",$line);
if($user_passї0]==$adduser){
echo "<h2>Duplicate Login. Invalid!</h2>";
return 0;
}
}
$add=$adduser.":".md5($addpass)."\n";
if(!fwrite($fh,$add)){
die("<p>Could Not Open Password File");
}
fclose($fh);
echo"<h2>User Added!</h2>";
}
$login=$_POSTї'login'];
$password=$_POSTї'password'];
$checkpass=$_POSTї'checkpass'];
$adduser=$_POSTї'adduser'];
$addpass=$_POSTї'addpass'];
$add=$_POSTї'add'];
$add_form=$_GETї'add_form'];
if(isset($checkpass)){
if(check_pass($login,$password)){
echo "<h2>Login Success!!</h2>";
}else{
echo "<h2>Login Failed</h2>";
print_login_form($login);
}
} elseif(isset($add_form)){
print_add_form();
} elseif(isset($add)){
add_user($adduser,$add_pass);
} else{
print_login_form("");
}
?>
<p>You can <a href=authentication.php?add_form=1>Add Users</a> or <a href=authentication.php>login</a> an existing user.