Why does this expression evaluate to true? - php

I am making php login function and I have come across a problem. In one part of the script I am testing whether all of the info is inserted in html form that is fed to the script via $_POST variable. And in one part, the script correctly evaluates whether only username is not entered or only password, and it correctly evaluates whether password is wrong BUT when I enter correct user/pass, it activates error "Username and password not entered". I can't figure it out. Is it possible that FLASE && FALSE equals TRUE?
---Edit----
Ok, I see now that I should included all of the relevant files in this question. So here they are:
index.php
<?php
session_start();
if (isset($_SESSION['login_message'])) {
$message = $_SESSION['login_message'];
unset($_SESSION['login_message']);
}
?>
<html>
<head>
<?php
require_once("include/head.php");
?>
</head>
<body>
<form action="auth/login.php" method="post">
<table>
<tr>
<td>
<img src="graphics/znak_hrz.png" alt="Znak HRZ" style="height: 200px; padding: 10px;">
</td>
<td>
<table style="padding: 10px;">
<tr>
<td><?php if (isset($message)) {echo "<td>" . $message . "</td>";}?></td>
</tr>
<tr>
<td>
<label for="username">Username:</label>
<input id="username" type="text" name="username" />
</td>
</tr>
<tr>
<td>
<label for="password">Password:</label>
<input id="password" type="password" name="password" />
</td>
</tr>
<tr>
<td style="text-align: center;">
<input type="submit" name="login" value="Login" />
</td>
</tr>
</table>
</td>
<td>
<img src="graphics/znak_eskadrile.png" alt="Znak eskadrile" style="height: 200px; padding: 10px;">
</td>
</tr>
</table>
</form>
</body>
</html>
login.php
<?php
session_start();
// This script will deny access if following conditions are met in that order:
// - Username not entered
// - Password not entered
// - Username and password not entered
// - User doesn't exist in the database
// - User is deactivated in the database
// - The password is wrong
// Upon successful login, it will redirect user to secure/index.php and
// upon unsuccessful login it will return him to index.php for another try.
// If username is not set, set an error message
if (empty($_POST['username']) && !empty($_POST['password'])) {
$_SESSION['login_message'] = "Username missing";
}
// If password is not set, set an error message
if (empty($_POST['password']) && !empty($_POST['username'])) {
$_SESSION['login_message'] = "Password missing.";
}
//If username AND password are not set, set an error message
if (empty($_POST['username']) && empty($_POST['password'])) {
$_SESSION['login_message'] = "Username and password empty.";
}
// Check if the username exists in the database and if the password is correct
if (!isset($_SESSION['login_message']) && !empty($_POST['username']) && !empty($_POST['password'])) {
require_once("database.php");
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
// Determine whether an account exists matching this username and password
$stmt = $auth_db->prepare("SELECT uid, pid, password, access_category, last_log, active FROM " . TBL_USERS . " WHERE username = ?");
// Bind the input parameters to the prepared statement
$stmt->bind_param('s', $username);
// Execute the query
$stmt->execute();
// Assign results of query to temporary variables
$stmt->bind_result($uid, $pid, $db_password, $access_category, $last_log, $active);
$stmt->fetch();
// If user doesn't exist in the database, deny login
if (!isset($uid)) {
$_SESSION['login_message'] = "User doesn't exist.";
}
// If user is deactivated, deny login
if (isset($uid) && !$active) {
$_SESSION['login_message'] = "User is deactivated.";
}
// If the password is wrong, deny login
if (isset($uid) && $active && $db_password != md5($password)) {
$_SESSION['login_message'] = "Wrong password.";
}
if (!isset($_SESSION['login_message'])) {
// Close previous statement
$stmt->close();
// Update the account's last_login column
$stmt = $auth_db->prepare("UPDATE " . TBL_USERS . " SET last_log = NOW() WHERE username = ?");
var_dump($stmt);
$stmt->bind_param('s', $username);
$stmt->execute();
// Set session variable
$_SESSION['username'] = $username;
$_SESSION['uid'] = $uid;
$_SESSION['pid'] = $pid;
$_SESSION['last_log'] = $last_log;
$_SESSION['active'] = $active;
$_SESSION['access_category'] = $access_category;
}
}
if (!isset($_SESSION['login_message'])) {
header('Location: ../secure/index.php');
} else if (isset($_SESSION['login_message'])) {
header('Location: ../index.php');
}
?>
secure/index.php
<?php
session_start();
require_once("../auth/login.php");
?>
<html>
<head>
<?php
#if($_SESSION['access_category'] == '0') {
# header('Location: eth93sl/');
#}
?>
</head>
<body>
<?php
echo "uid:" . $_SESSION['uid'] . "<BR>";
echo "username: " . $_SESSION['username'] . "<BR>";
echo "active: " . $_SESSION['active'] . "<BR>";
echo "last_log: " . $_SESSION['last_log'] . "<BR>";
echo "access_category: " . $_SESSION['access_category'] . "<BR>";
?>
</body>
</html>

The problem was that the login.php script was executing twice because of the line three in secure/index.php, a remnant line from another login system I was experimenting with. And second time that the script got called, it had no $_POST data, hence no username and no password so the apropriate conditional got activated.
Reminded me that when I come across a problem, it is always good to broaden my view to other files as well.

Related

Data not displaying correctly after user logs in through login form in PHP

The code below is of my user login form. But, after the username and password matches and the page is being redirected, it shows error 'Undefined index in username in [path]'.
<?php
session_start();
require_once "dbreg.php";
$errormsg = array();
$errorcount = 0;
if (!empty($_POST)) {
if (empty($_POST['username'])) {
$errormsg[] = "Enter valid username";
$errorcount++;
}
if(empty($_POST['password'])) {
$errormsg[] = "Please enter password";
$errorcount++;
}
if(!empty($_POST['username'])) {
$userquery = mysql_query("SELECT * FROM regform WHERE username='".$_POST['username']."'");
$useroutput = mysql_fetch_assoc($userquery);
if (empty($useroutput)) {
$errormsg[] = "Invalid username or password";
$errorcount++;
}
else {
$queryoutput = mysql_query("SELECT * FROM regform WHERE username = '".$_POST['username']."' AND userpass = '".$_POST['password']."'");
$newoutput = mysql_fetch_assoc($queryoutput);
if (empty($newoutput)) {
$errormsg[] = "Please enter valid login and password";
$errorcount++;
}
else {
$_SESSION['uid'] = $newoutput['id'];
header("Location: http://localhost/classwork2/userprofile.php");
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login form</title>
</head>
<body>
<h1>Login</h1>
<?php
if (!empty($errormsg)) {
for ($i=0; $i < count($errormsg) ; $i++) {
# code...
?>
<div style="color:red"><?php echo $errormsg[$i]; ?></div>
<?php
}
}
?>
<table border="1">
<form name="lognow" id="lognow" action="reglogin.php" method="post" enctype="multipart/form-data">
<tr>
<td>
<label>Username</label>
</td>
<td>
<input type="text" name="username" id="username">
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="text" name="password" id="password">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Login">
</td>
</tr>
</form>
</table>
<h3>Or</h3>
<h2>
Click Here to Register.
</h2>
</body>
</html>
And below is the code to the userprofile.php page
<?php
session_start();
require_once "dbreg.php";
$sql = "SELECT firstname, lastname FROM regform WHERE username = '" . $_SESSION['username'] . "'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo "Hello, " . $row['firstname'] . $row['lastname'] ;
?>
Will be kind if anyone can guide me what am i doing wrong. Also if i keep the above code inside an if(!empty($_POST['username'])) the page displays blank.
The problem is, you never did/set $_SESSION['username'] = "YOUR_USERNAME" after successful login, you just did $_SESSION['uid'] = $newoutput['id']; and redirected the user to userprofile.php page.
So the solution is, construct your query based on user's id, rather than user's username. In userprofile.php page, change the query like this:
$sql = "SELECT firstname, lastname FROM regform WHERE id = '" . $_SESSION['uid'] . "'";
// your code
Sidenote: mysql_* functions are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

Login form using PHP not verifying password_verify successfully, even though values are correct

Thanks in advance for any advice on this one. I'm a bit of a newbie and am having some problems with a login form using password_verify. My code is as follows -
<?php
error_reporting(E_ALL); ini_set('display_errors', true);
require_once('includes/config.inc.php');
$page_title = 'Login';
include('includes/header.php');
if(isset($_POST['submitted'])){
require_once(MYSQL);
if(!empty($_POST['email'])) {
$e = mysqli_real_escape_string($dbc,$_POST['email']);
} else {
$e = FALSE;
echo '<p class="error">You forgot to enter your email address</p>';
}
//Validate the password
if(!empty($_POST['pass'])) {
$p = $_POST['pass'];
} else {
echo '<p class="error">You forgot to enter your password</p>';
}
if ($e && $p) { // If everything is OK
//Query the DB to get hash for confirmation purposes
$hashquery = mysqli_query($dbc,"SELECT password from users WHERE email = '$e'");
while ($row = $hashquery->fetch_assoc()) {
$hash = $row['password'];
}
//Echo details for verification purposes
echo "The email address you entered was: " .$e."<br />"; //to verify
echo "The password you entered was: " . $p."<br />"; //to verify
echo "The password has from the db is" .$hash."<br />"; //to verify
$verify = password_verify($p,$hash);
if ($verify) {
echo "successful"; } else { echo "Unsuccessful";
}
//End verification
//run the login query
$q = "SELECT user_id, user_level, password from users WHERE email = '$e' AND active is NULL";
$r = mysqli_query($dbc,$q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if ($r) { //A match was made
//register the values and redirect
$row = mysqli_fetch_row($r);
$user_id = $row[0];
$user_level = $row[1];
$password = $row[2];
}
$verify = password_verify($p, $password);
if ($verify) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_level'] = $user_level;
$url = BASE_URL . 'index.php'; //Define the url
ob_end_clean(); //Delete the buffer
header("Location: $url");
} else {
echo '<p class="error">We could not verify the details you entered.</p>';
}
} else { //If everything wasn't OK
echo '<p class="error">Please try again.</p>';
}
mysqli_close($dbc);
}
?>
<h1>Login</h1>
<p>Your browser must allow cookies in order to log in</p>
<form action="login.php" method="post">
<fieldset>
<p><b>Email Address</b><input type="email" size="20" maxlength="80" name="email"/></p>
<p><b>Password</b><input type="password" size="20" maxlength="80" name="pass"/></p>
<div align="center"><input type="submit" value="Login" name="submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</fieldset>
</form>
<?php
include('includes/footer.php');
?>
The site is at http://scottsathome.com/database/login.php
When I enter the username 'justin#scottsathome.com' and the password 'password', as you'll see at the top of the page, the verify_password query returns sucessful.
However in the below query, where I actually want to log in, I constantly get the "We are unable to verify your details" message and not logged in.
Could someone please explain a possible solution to this problem?
Many Thanks,
Justin.

Issue With Resetting Password using a update md5 password

I am wanting to use a html form to reset passwords to a hashed md5 password. I will include all of my code. i get a blank screen when i submit the form. I am a beginner so please keep that in mind. I check myphpadmin and the hashed password does not change.
<html>
<head><title> Administrator reset password page</title></head>
<body>
<form action="forgotpass.php" method="post">
<table>
<tr><td>User Name:</td><td><input type="text" name="password" /></td></tr>
<tr><td>Password:</td><td><input type="text" name="user" /></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Reset Password"/></td> </tr>
</table>
</form>
</body>
</html>
<?php
include "connect.php"
$tmpPass = $_POST['password'];
$tmpuser= $_POST['user'];
$tmpPass = md5($tmpPass);
$sql = mysql_query("UPDATE employee set pass = $tmpPass WHERE usr = $tmpuser");
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) {
echo 'Password Has Been Reset Successfully';
/*
$email_message.= "Hello ";
$email_message.= "User with username: " .$tmpUser. "\n";
$email_message.= "Your New password: " .$_POST['password']. "\n";
$email_to = "registration#joshuamoorehead.com";
$email_subject = "Registration";
*/
else {
echo 'Error: '. $conn->error;
}
$conn->close();
?>
You're missing quotes around your string values:
$sql = mysql_query("UPDATE employee set pass = '$tmpPass' WHERE usr = '$tmpuser'");
Also, why are you running your query a second time?
// Performs the $sql query on the server to insert the values
if ($conn->query($sql) === TRUE) { // <-- HERE
echo 'Password Has Been Reset Successfully';
Your $sql variable will contain the boolean result of your query, you need to check that variable is true as opposed to running the query again:
if($sql === true) {
echo 'Password Has Been Reset Successfully';

PHP-Form validation and insertion using MySql

I'm using this code to validate my my html form and I now need to add the form data into a table in mysql. How do I proceed I know the basics of creating a connection and sql databases but since I've already used the form's submit button i don't know how to get the data to a place where I can insert it again
<?php
// define variables and initialize with empty values
$nameErr = $passErr = $emailErr =$cpassErr="";
$name = $pass = $cpass = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$nameErr = "Enter Username";
}
else {
$name = $_POST["username"];
}
if (empty($_POST["password"])) {
$passErr = "Enter password";
}
else {
$pass = $_POST["password"];
}
if (empty($_POST["cpassword"])) {
$cpassErr = "Retype password";
}
else {
$cpass= $_POST["cpassword"];
}
if (empty($_POST["email"])) {
$emailErr = "Enter email";
}
else {
$email = $_POST["email"];
}
}
?>
<html>
<head>
<style>
.error {
color: #FF0000;
}
</style>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table border="0" cellspacing="20">
<tbody>
<tr>
<td>Username:</td>
<td><input type="text" name="username" accept="" value="<?php echo htmlspecialchars($name);?>">
<span class="error"><?php echo $nameErr;?></span>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" accept="" value="<?php echo htmlspecialchars($pass);?>">
<span class="error"><?php echo $passErr;?></span></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="text" name="cpassword" accept=""value="<?php echo htmlspecialchars($cpass);?>">
<span class="error"><?php echo $cpassErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" accept="" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td></td>
</tr>
</tbody>
</table>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Code for the connection
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="LSDB";
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
var_dump($_POST);
$u=$_POST['username'];
$p=$_POST['password'];
$e=$_POST['email'];
$ph=$_POST['phone'];
$sql="INSERT INTO register (username,password,email,phone)
VALUES
('$u','$p','$e','$ph')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
first off i would suggest you escaping the inputs.
also worth noting you could use prepared statements and object oriented way of mysqli as most of the documents on OO are clearer than the procedural way.
like :
<?php
$u=striptags($_POST['username']);
$p=striptags($_POST['password']);
$e=filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$ph=(int)$_POST['phone'];
$mysqli = new mysqli($host,$username,$password,$db_name);
$query = "INSERT INTO register (username,password,email,phone) VALUES (?,?,?,?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("sssi", $u, $p, $e, $ph);
$stmt->execute();
$mysqli->close();
?>
it would not also hurt using hash on your password like :
<?php
$salt = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$passh = crypt($pass, '$6$'.$salt);
?>
do note that you will need to store the salt in mysql also so you can compare it later
so with these your passwords are safer and if your database gets stolen the passwords will remain hashed.
When the user submits the form, if the validation was successful, then you should execute a process function, where you can place as much instructions as you need, including storing the data in a database, or printing it in an auto-generated webpage. Everything you need.
In another order of things, looks like that code of you is too simple and hence vulnerable to cross-site scripting. You should not only validate if the fields are empty or not, but also you should use some regular expressions and the function preg_match( ) to filter which characters are entered. The best protection is to allow the user enter only the characters that are needed in each field, and not any others than those.
Example on how to handle the logic of the form:
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
// The data sent is valid, hence process it...
process_form();
}
} else {
// The form has not been sent, hence show it again...
show_form();
}

PHP User Authentication [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've been teaching myself PHP out of a couple of books, from the W3Schools site and using a whole bunch of posts of Stack Overflow.
To try and put something into practice I'm trying to make a small image gallery that implements a user authentication system. Users have a security access that determines wether they have read, read write access or can administrate other users etc. I've only gotten as far as the login and add user stuff.
I've modelled it off my work, where everyone has a unique employee ID and 8 digit email ID.
I know this is a long shot, but I'm just wondering if anyone would be able to take a look and tell me if my code is heading down the right track? It's so different putting something 'real world' like this together from the basic examples provided in books. Any comments and suggestions would be appreciated....
login.php
<!DOCTYPE html>
<?php
// Connect to the database
include('./helpers/db.php');
include('./helpers/general.php');
// Check if the user has submitted their details.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$loginId = htmlspecialchars(($_POST['userId']));
$loginPass = htmlspecialchars(sha1($_POST['password']));
// Check if they've submitted blank details.
if (!checkLoginId($loginId) || (!checkPassword($_POST['password']))) {
$errorMsg = "Please enter a valid username or password!";
}
else {
// Select the details we want for the session info.
$stmt = $dbh->prepare("SELECT firstName, lastName, securityLevel FROM
userDetails WHERE registeredNumber = :loginId
AND password = :loginPass" );
$stmt->bindParam(':loginId', $loginId);
$stmt->bindParam(':loginPass', $loginPass);
$stmt->execute();
// Make sure the user is found, and that there security level is 1 or more.
if ($stmt->rowCount() > 0) {
$userDetails = $stmt->fetch();
if ($userDetails['securityLevel'] < 1) {
$errorMsg = "Insufficient access for this user.";
}
else {
// Start a new session and set up the regularly used info.
session_start();
$_SESSION['loggedIn'] = 1;
$_SESSION['userID'] = $loginId;
$_SESSION['fname'] = $userDetails['firstName'];
$_SESSION['lname'] = $userDetails['lastName'];
$_SESSION['security'] = $userDetails['securityLevel'];
header("Location: ./browser/");
}
}
else {
$errorMsg = "Invalid User ID or Password!";
}
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<style type="text/css">
body {font-family:sans-serif;}
.warning {color:red;font-weight:bold;}
#login {margin-left:auto;margin-right:auto;width:200px;border-style:solid;border-width:1px;padding:20px;}
</style>
<body>
<!-- Display the login form -->
<div id="login">
<form action="login.php" method="POST">
<?php
if (isset($errorMsg)) {
echo '<span class="warning">'. $errorMsg . '</span>';
}
?>
<p><label for="userId">User Name:</label><br />
<input type="text" maxlength="5" name="userId"
title="Enter your User ID:">
</p>
<p><label for="pasword">Password:</label><br/>
<input type="password" maxlength="12" name="password"
title="Enter your password:"/>
</p>
<p><input id="submit" type="submit" name="submit" value="Submit"></p>
</form>
</div>
</body>
db.php
<?php
$hostname = 'localhost';
$dbname = 'dam';
$dbuser = 'root';
$dbpass = '****';
// Try and connect to the database and catch the error if it doesn't work.
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
echo "Connected to Database<br/>";
}
catch (PDOException $e)
{
print "Error! " . $e->getMessage() . '<br/>';
die();
}
?>
general.php
<?php
// Checks wether the loginID/Registered Number is valid
function checkLoginId($login) {
if ($login == '' || $login == NULL || (!is_numeric($login))) {
return 0;
}
else return 1;
}
// Checks whether the password is valid
function checkPassword($password) {
if ($password == '' || $password == NULL) {
return 0;
}
else return 1;
}
function verifyNewUser($userID, $upass, $fname, $lname, $email) {
$hasErrors = 0;
$errorMsg = array();
if ($userID == '' || $userID == NULL || (!is_numeric($userID)) || (strlen($userID) != 5)) {
$hasErrors++;
$errorMsg[] = "User ID is either missing, or does not have 5 digits";
}
if ($upass == '' || $upass == NULL || (strlen($upass) < 6)) {
$hasErrors++;
$errorMsg[] = "Password is either missing, or does not meet minimum length of six";
}
if ($fname == '' || $fname == NULL || empty($fname)) {
$hasErrors++;
$errorMsg[] = "First name is missing.";
}
if ($lname == '' || $lname == NULL || empty($lname)) {
$hasErrors++;
$errorMsg[] = "Last name is missing.";
}
if ($email == '' || $email == NULL || empty($email) || (strlen($email) != 8)) {
$hasErrors++;
$errorMsg[] = "Check email id, should be 8 characters.";
}
if ($hasErrors == 0) {
return 1;
}
else {
echo "Returning with errors<br/>";
return $errorMsg;
}
}
?>
adduser.php
include ("./helpers/general.php");
include('./helpers/db.php');
session_start();
// If the user isn't logged in, send them away...
if (!(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] != '')) {
header("Location: ./login.php");
exit();
}
// Get the users full name so we can politely tell them to rack off if they
// don't have sufficient access to add users.
$uname = $_SESSION['fname'] . ' ' . $_SESSION['lname'];
// Check if the user has the security clearence to add a new user:
if ($_SESSION['security'] != 4) {
echo "Sorry $uname, only level 4 administrators can manage users.<br/>";
echo 'Back to Browser';
exit();
}
// Check if they have submitted the form and validate the input
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userID = htmlspecialchars($_POST['registeredNumber']);
$upass = htmlspecialchars($_POST['password']);
$fname = ucfirst(htmlspecialchars($_POST['firstName']));
$lname = ucfirst(htmlspecialchars($_POST['lastName']));
$email = htmlspecialchars($_POST['emailID']);
$secLev = $_POST['securityLevel'];
$creator = $_SESSION['userID'];
$valid = verifyNewUser($userID, $upass, $fname, $lname, $email);
if ($valid == 1) {
// Encrypt the password
$upass = sha1($upass);
// Create the array to feed the SQL statement.
$data = array($userID, $upass, $fname, $lname, $email, $secLev, date('Y-m-d H:i:s'), $creator);
$dbh->beginTransaction();
$stmt = $dbh->prepare("INSERT INTO userDetails VALUES('', ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute($data);
$dbh->commit();
if ($stmt->rowCount() > 0) {
echo "Success, new user $fname $lname added!<br/>";
echo "Email ID: $email<br/>";
echo "Security Level: $secLev<br/>";
}
}
else if (isset($valid)) {
foreach($valid as $error) {
echo '<span style="color:red;font-weight:bold">' . $error . "<span><br/>";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add A New User</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="adduser.php" method="post">
<table>
<tr>
<td><label for="registeredNumber">Registered Number:</label></td>
<td><input type="text" maxlength="5" name="registeredNumber"/></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" maxlength="12" name="password"/></td>
</tr>
<tr>
<td><label for="firstName">First Name:</label></td>
<td><input type="text" maxlength="20" name="firstName"/></td>
</tr>
<tr>
<td><label for="lastName">Last Name:</label></td>
<td><input type="text" maxlength="20" name="lastName"/></td>
</tr>
<tr>
<td><label for="emailID">Email ID:</label></td>
<td><input type="text" maxlength="8" name="emailID"/></td>
</tr>
<tr>
<td><label for="securityLevel">Security Level:</label></td>
<td>
<select name="securityLevel">
<option value="0" selected="selected">0 - No Access</option>
<option value="1">1 - Read Access</option>
<option value="2">2 - Read/Write Access</option>
<option value="3">3 - Read/Write/Delete Access</option>
<option value="4">4 - User Administrator</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
logout.php
<?php
// Destroy the session and go to the login screen.
session_start();
session_destroy();
header("Location: login.php");
?>
There are serious security problems with your approach.
The biggest problem is you are storing the password in the database. You do not need to store the password in the database, that is a terrible idea that could be grounds for someone to sue your pants off in court.
There are a variety of encryption and hashing options to let you build a system like this without storing the password in the database, and it is standard procedure to use one of them. Anybody who doesn't is asking for problems in future (google search for "PSN password leak").
One good option is PBKDF2 http://en.wikipedia.org/wiki/PBKDF2
However, that is just the most obvious problem. There are some other things you're not doing perfectly and this really is something you need to learn how to do properly, or you should not attempt it at all. Even if you're using PBKDF2 you still need to learn how to use it properly.
I recommend listening to almost every episode of Security Now before attempting to write your own authentication system. http://www.grc.com/securitynow.htm

Categories