Hi guys I'm having a bit of a problem with my PHP logon script, this is for an assignment of mine at uni and for some reason PHP just confuses me but programming such as Java etc. I can deal with fine. Anyways the script works as far as I can, except it seems to accept every username and password.
This is a text based logon as per the assignment requirement. Any help/tips are much appreciated!
login.html
Code:
<html>
<head>
<title>
Login script
</title>
</head>
<form method="post" action="login.php">
<h2>Please login</h2>
Name:
<input type="text" name="name"><br>
Password:
<input type="password" name="pass"><br>
<input type="submit" value="submit">
</form>
<br>
<a href="register.html">New users may register here</a><br>
</html>
login.php
Code:
<?php
session_start();
$getname=trim($_POST["name"]);
$getpass=trim($_POST["pass"]);
$_SESSION["name"]=$getname;
$_SESSION["pass"]=$getpass;
$encrypted=md5($getpass);
if ($getname) {
// search for login name and password in the file
$namefound=false;
$passfound=false;
// check name and password against users file
// which has format user:encrypted-password
// open file
$fh=fopen("users.txt","r");
// read whole file into a string variable
$filecontents=fread($fh,filesize("users.txt"));
fclose($fh);
//convert string variable to an array
// using end of line as delimiter
$users=explode("\n", $filecontents);
//check array for existence of name
// $line is one item in $users array
foreach ($users as $key=>$line) {
// convert each $line to an array called $fields
// using colon as delimiter
// so first field is $fields[0], 2nd field is $fields[1]
$fields=explode(":", $line);
// compare name entered with first field in line
// assuming password was not blank
if ($fields[0] == $getname) {
//User name was `found
$namefound=true;
// check for match of 2nd field with password entered
if ($fields[1] == $encrypted) {
//password match found
$passfound=true;
// could break out of loop here
} else {
// only used this for debugging
//echo "$pass does not match $fields[1]<br>";
}
} else {
// only used this for debugging
//echo "$name does not match $fields[0]<br>";
}
}
if ($namefound=true) {
if ($passfound=true) {
// jump to the main menu, which will have the session variables available
header ("Location: menu.php");
}
else {
// the name was OK but not the password
echo "Password incorrect. Please try again.<br>";
}
}
else {
// a name has been submitted but was not found in the file
if ($getname) {
echo "Incorrect user name \"$getname\"<br>";
echo "Please try login again or register new user below<br>";
}
echo "<a href=\"register.html\">New users may register here</a><br>";
}
}
?>
the text file needs to be users.txt obviously with format being
If you can at least point out where I might be going wrong that would be great