When I run this page, everything shows up correctly, but then when I try to test my various error messages, my button keeps redirecting me back to my login page as if everything was inputted correctly. It fails to register the if blocks I've included. Below is the php (the html runs fine, not included).
*Side note, a few lines are commented out because I initially had PDO and am changing them over to mysql, but those shouldn't affect everything else running. I have them commented out too so if things did work, I wasn't adding unnecessary info to my database.
Of course, PHP is not skipping anything. It is diligently running your conditions, but in your code the only condition that affects the insert is the last one.
To make it work as desired you have to change all your ifs to elseif save for the first one
The problem: Your error may be set, but your INSERT will execute only if $password == $password2 which will be true if they're both empty.
You need to indicate alternative paths by doing else if
<?php
error_reporting (E_ALL);
$error = "";
if (isset($_POST['createAccount'])){
$username = $_POST['username'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$address = $_POST['address'];
$city = $_POST['city'];
$province = $_POST['province'];
$postalCode = $_POST['postalCode'];
if (!$username){
$error = "<br><div><em>No username entered.</em></div>";
}
elseif (!$password || !$password2){
$error = "<br><div><em>Missing password.</em></div>";
}
elseif (!$firstName || !$lastName){
$error = "<br><div><em>Please enter first and last name.</em></div>";
}
elseif (!$address || !$city || !$province || !$postalCode){
$error = "<br><div><em>Insufficient address provided. Please fill in all fields.</em></div>";
}
elseif ($password != $password2){
$error = "<br><div><em>Passwords do not match.</em></div>";
}
else{
$conn = mysql_connect(<blocked out for privacy reasons>);
$db = mysql_select_db("grocery", $conn);
$account = mysql_query("SELECT *
FROM accounts
WHERE username = '$username'",
$conn);
$rowExist = mysql_num_rows($account);
if ($rowExist == 1){
$error = "<br><div><em>Username already exists.</em></div>";
}
else {
//$newAccount = ("INSERT INTO accounts (username, password, first_name, last_name, street, city, province, postal_code)
// VALUES ('$username','$password','$firstName','$lastName','$address','$city','$province','$postal_code')");
//$conn->exec($newAccount);
header("location: GroceryLogin.php");
}
mysql_close($conn);
}
}
// I'm guessing here you do an echo $error;
Related
I am building a website's login page for an assignment. When I hash the password in the file that checks the users details it doesn't match with the stored hashed password in the database. The code always goes to the last else statement and relinks me to the login page with the wrong password sv equal to 1. If I don't hash the password, then copy and paste the hashed password from the database into the login form the login works. If anyone can help this would be greatly appreciated
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"];
$pass1 = $_POST["pass"];
$pass = hash('sha256', $pass1);
if(isset($_SESSION['user_type']))
{
unset($_SESSION['user_type']);
}
include("group_detail.php");
$query = "SELECT * from employee WHERE email = '$email' AND password = '$pass'";
$result_employee = $db->query($query);
$employee_row = mysqli_fetch_assoc($result_employee);
if(!empty($employee_row)){
$_SESSION['id'] = $employee_row['employee_ID'];
$_SESSION['name'] = $employee_row['name'];
$_SESSION['user_type'] = $employee_row['title'];
header('Location: homepage.html');
}else{
$query = "SELECT * from customer WHERE email = '$email' AND password = '$pass'";
$result_customer = $db->query($query);
$customer_row = mysqli_fetch_assoc($result_customer);
if(!empty($customer_row)){
$_SESSION['id'] = $customer_row['customer_ID'];
$_SESSION['name'] = $customer_row['name'];
$_SESSION['user_type'] = 'Customer';
$_SESSION['email'] = $customer_row['email'];
header('Location: homepage.html');
}
else{
$_SESSION['wrong_password'] = 1;
header('Location: login.php');
}
}
The registration code
<<?php
// this code checks all reuired fields are filled in appropriately
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$nameErr = $phoneErr = $emailErr = $passwordErr = "";
$name = $address = $eircode = $email = $password = $phone = "";
$employee_ID = 0;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo $nameErr;
if (empty($_POST["name"])) {
$nameErr = "Your name is required for registration";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and a space allowed";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Your phone number is required for registration";
} else {
$phone = test_input($_POST["phone"]);
}
if(empty($_POST['email']))
{
$emailErr = "Your Email is required for registration";
} else {
include ("group_detail.php");
$email_test = test_input($_POST["email"]);
$sql = "SELECT * from customer WHERE email = '$email_test'";
// Checks if another account uses this email
$result = $db->query($sql); // runs the query
$num_rows_3= mysqli_num_rows($result); // counts how many rows the query applies to
if($num_rows_3 == 0){
// Sets email value if no one else has used this email to sign up before
$email = test_input($_POST["email"]);
}
else{
// Lets the customer know this email is already in use
$emailErr = "Another account has previously been registered with this email. If this is you, you can login ";
}
}
if(empty($_POST['pass1']))
{
$passwordErr = "Password required";
} else {
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
if($pass1 == $pass2){
$pass = hash('sha256',$pass1);
// $pass = $pass1;
} else{
$passwordErr = "The passwords you enter must match";
}
}
if(empty($_POST['address']))
{
$address = "";
}else{
$address = test_input($_POST['address']);
}
if(empty($_POST['eircode']))
{
$eircode = "";
}else{
$eircode = test_input($_POST['eircode']);
}
if ($phoneErr == "" && $nameErr == "" && $passwordErr == "" && $emailErr == "")
{
// This code enters the data from the form into the customer table
include ("group_detail.php");
$q = "INSERT INTO customer(";
$q .= "name, phone, password, email, address, eircode";
$q .= ") VALUES (";
$q .= "'$name', '$phone', '$pass', '$email', '$address', '$eircode')";
$result = $db->query($q);
$sql = "SELECT customer_ID FROM customer ORDER BY customer_ID DESC LIMIT 1";
$result1 = $db->query($sql);
$row = mysqli_fetch_assoc($result1);
$_SESSION['customer'] = $row['customer_ID'];
header('Location: homepage.html');
}
}
?>
Solution
Your field is of the incorrect length. When you use the SHA256 hash function you get an output similar to:
ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f // password123
If you're password field is only 15 characters then the saved value will be truncated:
ef92b778bafe771
However, during the comparison the full value from the logon script is used against the truncated version stored in the DB and therefore there is no match. Because, as you can see above, they aren't the same.
To fix you need to ALTER the table so that the field is at least varchar(64). Then new accounts will work as expected (note: old hashes still won't work - they need to be redone!)
Additional information
There are a few other issues with your code...
You shouldn't be putting variables directly into your code. Instead it is preferred to use a Prepared Statement with parametrised queries where you bind the variables later.
Which basically means in the query we use a place holder ? where we want a variable and then bind variables to the place holders later on
This is mainly to prevent SQL injection and protect you from incorrect input
It is best to use the PHP built in functions password_* to hash and verify passwords.
It's more secure than simply using hash
salts are auto-generated which protects you from things like rainbow tables
The default algorithm for password_hash requires a field length of 60+ characters
There's no need to store excess data in SESSION
The data is already stored in the DB so just fetch it as and when needed
It seems that you have one table for customers and another for employees
This isn't a good design there should be one table for users and then you can set flags for employee, customer, supplier etc.
Your test_input function carries out functions that are usually done on display not on save.
Below is a quick re-write that addresses some of the above (note: the below code is not complete it doesn't, for example, carry out all of the same validation - e.g. checking for illegal characters - it's just for illustrative purposes)
Register
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$errors = [];
$name = $_POST["name"] ?? null;
$phone = $_POST["phone"] ?? null;
$email = $_POST['email'] ?? null;
$address = $_POST['address'] ?? null;
$eircode = $_POST['eircode'] ?? null;
$pass1 = $_POST['pass1'] ?? null;
$pass2 = $_POST['pass2'] ?? null;
// Check passwords are the same and assign hash to $pass
$pass = $pass1 === $pass2 ? password_hash($pass1, PASSWORD_DEFAULT) : null;
// Check the required fields are present and not empty
if (!$name || !$phone || !$email || !$pass) {
$errors[] = "Required fields are missing.";
}
// Check if the email address already exists in the DB
$checkEmailExistsSQL = "SELECT COUNT(*) as countEmails FROM user WHERE email = ?";
$checkEmailExistsQuery = $mysqli->prepare($checkEmailExistsSQL);
$checkEmailExistsQuery->bind_param("s", $email);
$checkEmailExistsQuery->execute();
$emailExists = $checkEmailExistsQuery->get_result()->fetch_assoc()["countEmails"];
if ($emailExists !== 0) {
$errors[] = "The email address already exists in the DB";
}
// Check if there were errors and output them; then exit the script
if (count($errors)) {
foreach($errors as $error) {
echo $error, PHP_EOL;
}
exit;
}
include("group_detail.php");
$insertSQL = "
INSERT INTO user
(name, phone, password, email, address, eircode)
VALUES
(?, ?, ?, ?, ?, ?)
";
$insertQuery = $mysqli->prepare($insertSQL);
$insertQuery->bind_param("ssssss", $name, $phone, $pass, $email, $address, $eircode);
$insertQuery->execute();
// Success the user is registered
Logon
<?php
ini_set('display_errors', true);
ini_set('log_errors', true);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$email = $_POST["email"] ?? null;
$pass = $_POST["pass"] ?? null;
// You can remove the old user id. But you don't need to
//
// There's no need to store excess data on the user in
// the SESSION super global; any data that you need
// access to can be retrieved from the DB at will.
// Copying data into SESSION only eats into memory.
unset($_SESSION["id"]);
// Check that something was submitted for email and password
if (!$email || !$pass) {
echo "Error: all fields need to be completed";
exit;
}
include("group_detail.php");
$sql = "SELECT id, password FROM user WHERE email = ?";
$query = $mysqli->prepare($sql);
$query->bind_param("s", $email);
$query->execute();
// Check to see if the email address is registered.
// Then check to see if the password is a match.
if (
!($user = $query->get_result()->fetch_assoc())
|| !password_verify($pass, $user["password"])
) {
echo "Error: the email address or password isn't correct";
exit;
}
// Success the user is logged on
//
$_SESSION["id"] = $user["id"];
I am coding a "social media site" for a class project, and I am having trouble in one section.
When first registering an account, the user must enter a username and password, and click a submit button. PHP code checks the inputs to make sure they're all valid and that there will not be any duplicates, and if everything passes, it adds in the username and password into a SQL table called "users". Users has 3 columns: username, password, and userID. userID is the primary key.
Once that process is completed, we redirect to a separate page, where the user can enter more personal information, such as first and last name, city, country, etc. This table, called "userInfo" has the columns: firstName, lastName, emailAddress, address, city, country, and userID. userID, once again, is the primary key.
What I'm trying to figure out is how to match the two user ID's in an insert statement. I have a form that gathers all the required information, but I am not sure how to set up the SQL query to make sure that users.userID matches userInfo.userID.
Here's my PHP for users (initial registration)
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
if(isset($_POST['submit'])){
// Get inputs
$username = $_POST['user'];
$password = $_POST['password'];
// Clean inputs and encrypt password
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);
$password = md5($password);
// Check username not empty
if (empty($username)) {
$error = "true";
$errorMessage = "Please enter a value for your username";
}
// Check username does not already exist
$checkUserQuery = "SELECT username FROM users WHERE username = '$username'";
$checkResult = $conn->query($checkUserQuery);
if($checkResult->num_rows > 0) {
$error = "true";
$errorMessage = "This username already exists";
}
// Username does not exist, add to database
else {
$insertUserQuery = "INSERT INTO users (username, password) VALUES('$username', '$password')";
$insertResult = $conn->query($insertUserQuery);
$_SESSION['username'] = $username;
header("Location: userInfo.php");
}
}
?>
Here's my PHP code so far for userInfo:
<?php
session_start();
require_once('dbConnect.php');
$error = "false";
$errorMessage = "";
$username = $_SESSION['username'];
if(isset($_POST['submit'])){
// Get inputs
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$emailAddress = "fakeEmailAddress#fakeyfakefake.com";
$address = $_POST['address'];
$city = $_POST['city'];
$country = $_POST['country'];
// Clean inputs
$firstName = mysqli_real_escape_string($conn, $firstName);
$lastName = mysqli_real_escape_string($conn, $lastName);
$address = mysqli_real_escape_string($conn, $address);
$city = mysqli_real_escape_string($conn, $city);
$country = mysqli_real_escape_string($conn, $country);
// Validate Inputs (Only validating first and last name, location entries are not required)
if(empty($firstName) || empty($lastName)) {
$error = "true";
$errorMessage = "Please enter your first AND last name";
}
else {
}
}
?>
Apologies if this is super messy. Databases are NOT my strong suit lol.
Many thanks to anyone who can help!
You'll want to get the mysqli_insert_id for your insert into the users table and pass that along (potentially via your $_SESSION) for creation in userInfo.
I am creating my first sign in/register function to my web site by following a online tutorial. Every thing seems to be working good , My problem is in the tutorial the php if ($_SERVER['REQUEST_METHOD'] == 'POST') is set in the index page which checks if all the fields and then inserts them into the DB . But for me this not seem to work. But if I put the code onto the page where the form action redirects after it works fine. Is this the right way to do it. I wouldn't like to think so because I would like to check all the variable before we move on.
So if someone would like to educate me on this would be great.
Here is my php code still not fully finished but i wanted to clear this up first.
This is used by include method
<?php
//setup some variables/arrays
$action = array();
$action['result'] = null;
//check if the form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";
$firstName = mysqli_real_escape_string($link,$_POST['firstName']);
$lastName = mysqli_real_escape_string($link,$_POST['lastName']);
$password = mysqli_real_escape_string($link,$_POST['sign-up-password']);
$confirmPassword = mysqli_real_escape_string($link,$_POST['password-confirm']);
$email = mysqli_real_escape_string($link,$_POST['email2']);
//quick/simple validation
if(empty($firstName)){ $action['result'] = 'error';}
if(empty($lastName)){ $action['result'] = 'error';}
if(empty($password)){ $action['result'] = 'error';}
if(empty($email)){ $action['result'] = 'error';}
if($password != $confirmPassword){ $action['result'] = 'error';}
if($action['result'] != 'error'){
$add = mysqli_query($link,"INSERT INTO `users` VALUES(NULL,'$firstName','$lastName','$password','$email',0)");
if($add){
//the user was added to the database
//get the new user id
$userid = mysqli_insert_id($link);
//create a random key
$key = $firstName . $email . date('mY');
$key = md5($key);
//add confirm row
$confirm = mysqli_query($link,"INSERT INTO `confirm` VALUES(NULL,'$userid','$key','$email')");
if($confirm){
//let's send the email
}
}else{
$action['result'] = 'error';
array_push($text,'User could not be added to the database. Reason: ' . mysql_error());
}
}else{
}
}
?>
I am working on a project and I have a registration form for users to fill out. The form then also populates the database with other variables.
For the life of me though, I cant figure out why the screen is loading a blank white page.. I have been following some tutorials from youtube and trying to apply them to my existing pages but so far no dice.
Here's the PHP code Im working with. The tutorial I followed worked flawlessly when used on a blank page, but once I edited it for my own use, it no longer wants to run:
<?php
if(isset($_POST['register'])){
$username = protect($_POST['username']);
$password = protect($_POST['password']);
$email = protect($_POST['email']);
$email2 = protect($_POST['email2']);
$password2 = protect($_POST['password2']);
$commname = protect($_POST['commname']);
$outpostname = protect($_POST['outpost']);
$special = protect($_POST['specialty']);
if($username == "" || $password == "" || $email == "" || $password2 == "" || $email2 == "" || $commname == "" || $outpostname == "" || $special == "no"){
echo "Please supply all required fields!";
}elseif(strlen($username) > 20){
echo "Username must be less than 20 characters!";
}elseif(strlen($email) > 100){
echo "E-mail must be less than 100 characters!";
}elseif(strlen($email2) > 100){
echo "E-mail verify must be less than 100 characters!";
}else{
$register1 = mysql_query("SELECT `id` FROM `user` WHERE `username`='$username'") or die(mysql_error());
$register2 = mysql_query("SELECT `id` FROM `user` WHERE `email`='$email'") or die(mysql_error());
if(mysql_num_rows($register1) > 0){
echo "That username is already in use!";
}elseif(mysql_num_rows($register2) > 0){
echo "That e-mail address is already in use!";
}else{
$spec = mysql_real_escape_string($_POST['specialty']);
$comnam = mysql_real_escape_string($_POST['commname'[);
$postnam = mysql_real_escape_string($_POST['outpost'[);
$ins1 = mysql_query("INSERT INTO `stats` (`credits`,`food`,`land`,`energy`,`turns`,`turns_max`,`gas`,`ore`,`population`,`buildeff`,`offpts`,`defpts`,`score`) VALUES (2000,2000,100,2000,30,30,2000,2000,500,100,0,0,0)") or die(mysql_error());
$ins2 = mysql_query("INSERT INTO `unit` (`trainee`,`juggernaut`,`infantry`,`marauder`,`terminator`,`reconsq`,`prisoner`,`destroyer`,`colossus`) VALUES (100,0,50,0,0,0,0,0,0)") or die(mysql_error());
$ins3 = mysql_query("INSERT INTO `user` (`colonynum`,`username`,`password`,`email`,`specialty`,`commname`,`outpostname`) VALUES (0,'$username','".md5($password)."','$email','$spec','$comnam','$postnam')") or die(mysql_error());
$ins4 = mysql_query("INSERT INTO `structure` (`agridome`,`spaceport`,`barrack`,`researchfac`,`laserbat`,`factory`,`infirmary`,`trainingfac`) VALUES (1,0,5,0,0,0,1,1,)") or die(mysql_error());
header('Location: aurora/main.php');
}
}
} ?>
I know its pretty "ugly" but I am trying to learn :)
if you need the form Im using let me know.. shouldnt matter though. I have all the ID's set right with correct spelling etc.
You have invalid syntax in your code, that is why showing blank screen. Replace this, Use $_POST['commname'] instead of $_POST['commname'[
$comnam = mysql_real_escape_string($_POST['commname']);
$postnam = mysql_real_escape_string($_POST['outpost']);
instead of
$comnam = mysql_real_escape_string($_POST['commname'[);
$postnam = mysql_real_escape_string($_POST['outpost'[);
Note: Use mysqli_* or PDO instead of using mysql_* functions(deprecated)
I have this problem with my web system. As administrator, my purpose is to register some users giving them username,password,firstname and lastname. I do that properly since all the records are inserted correctly. But when I'm trying to have access as one of those users, I cannot enter, geting the message "Username and password do not match". This is my login check code:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $_POST['username'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
}
}
else { // Run this code if login_check is equal to 0 meaning they do not exist
do_html_header('');
echo '<h3 style="color:#800000;">The Username And Password do not match.</h3><br><br></br></br>';
display_login_form();
}
Apparently, there is a problem with my while loop. But it does work properly for those users inserted in my database via MySql console of wampserver. The problem exists only for the users inserted via the web site.
The part of code that I use to insert new users (servers) is :
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$role = $_POST['role'];
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
//$username= $_SESSION['username'];
if (isset($_POST['username'])) {
if (isset($_POST['password'])) {
if (isset($_POST['firstname'])) {
if (isset($_POST['lastname'])) {
if(isset($_POST['role'])) {
$insertServer = mysql_query("INSERT INTO servers (username,password,firstname,lastname,role) VALUES('".$username."',sha1('".$password."'),'".$firstname."','".$lastname."','".$role."')")or die(mysql_error());
echo "<h5 style=color:#800000><i>The server ".$username." is now registered </i></h5>";
display_manager_menu();
}
}
}
}
}
Any ideas please?
Look at the table you INSERT the data ('servers'). It's different from the table you SELECT the data from ('members').
Don't use the mysql_query function, as it deprecated. Try using PDO or mysqli_query instead.
Don't ever use unfiltered input in your query.
Try using more secure functions for your login/registration form (like bcrypt, or password_hash). Look here.