First, I am sorry my code is VERY LONG, but my professor wants it all on one page instead of in separate pages and the requirements are lengthy. Also, this is for practice and not a real username and password site. I am required to use salting instead of the password hashing function as well.
The issues that I am running into right now (might have others after I can figure these ones out and test some more. I have been writing this code for days now and am beyond confused since I thought I had it figured out.
-
When the link is clicked to create a new account, the URL is updating with the
GET
variables but the code is not running to change the form displayed on the same page to the new account info instead of the login info. I am trying to trigger this change via theGET
with the$show
and$new
variables. -
I am getting this error when I try to add in a username and password (and click submit) which is why I am guessing it is not connecting to the database as well. the line it refers to is
$stmt = mysqli_stmt_init($conn);
.
Fatal error : Uncaught TypeError: mysqli_stmt_init(): Argument #1 ($mysql) must be of type mysqli, string given in C:\xampp\public_html\csis2440\less-insecure\index.php:302 Stack trace: #0 C:\xampp\public_html\csis2440\less-insecure\index.php(302): mysqli_stmt_init(ââ) #1 C:\xampp\public_html\csis2440\less-insecure\index.php(377): usernameExists(ââ, âwerweâ) #2 C:\xampp\public_html\csis2440\less-insecure\index.php(31): loginUser(ââ, âwerweâ, âwerweâ) #3 {main} thrown in C:\xampp\public_html\csis2440\less-insecure\index.php on line 302
More questions may follow once I can actually test the code upon moving past these errors. Thank you for your help.
End Goal: (seems to be easier than I have made it but I am new and alas make things difficult on myself)
-
Process all information on the same page.
-
A login form is displayed, if a user enters their login info then it looks to the database to see if they have an account. If so then âaccess is grantedâ and the form is not displayed anymore. If not, then âaccess deniedâ and the form shows with the error message that is applicable.
-
If the user clicks on the New Account link, then another form is shown instead (looks the same but the header should be different). If filled out the username and password are inserted into the database. If the username already exists and an error is displayed.
My database includes: a table called user_info and it contains 3 rows: id (auto incremented), username, password.
<?php
session_start();
//VARIABLES
$userError = $passError = $msg = $username = $password = $welcome= $welcomes = $conn = "";
$show = true;
$new = false;
//ARRAY
$welcome = array("Hola","Aloha","Bonjour","Hallo","Ciao","Konnichiwa",);
if(isset($_GET['show']))
{
$show=true;
}
if(isset($_GET['new']))
{
$new=true;
}
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
//GET THE POST VARIABLES
$username = $_POST['username'];
$password = $_POST['password'];
//USERNAME AND PASSWORD ENTERED AND SUBMIT BUTTON CLICKED
if(isset($_POST["submit"]))
{
dbconn();
if(emptyInputLogin($username, $password) !== false)
{
header("location: index.php?error=emptyinput");
$msg = 'Access Denied';
$show = true;
$new = false;
exit();
}
else
{
loginUser($conn, $username, $password);
header("location: index.php?");
$msg = 'Access Granted';
$show=false;
$new = false;
exit();
}
}
//SIGN UP SUBMIT BUTTON CLICKED
elseif (isset($_POST['newsubmit']))
{
dbconn();
if(emptyInputSignup($username, $password) !== false)
{
header("location: index.php?error=emptyinput");
$show = false;
$new = true;
exit();
}
if(invalidUsername($username) !== false)
{
header("location: index.php?error=invalidusername");
$show = false;
$new = true;
exit();
}
if(usernameExists($conn, $username) !== false)
{
header("location: index.php?error=usernametaken");
$show = false;
$new = true;
exit();
}
createUser($conn, $username, $password);
}
//IF CLEAR HAS BEEN CLICKED
elseif(isset($_POST['reset']))
{
$username = "";
$password = "";
}
//LOG OUT BUTTON CLICKED
elseif (isset($_POST['out']))
{
logout();
$show = true;
$new = false;
}
//SIGNUP BUTTON CLICKED
elseif(isset($_POST['create']))
{
$show = false;
$new = true;
}
//ALREADY HAVE ACCOUNT BUTTON CLICKED
elseif(isset($_POST['already']))
{
$show = true;
$new = false;
}
else
{
header("location: index.php?");
$show = true;
$new = false;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css\style.css">
<script src="js\script.js" defer></script>
<title>Less Insecure</title>
</head>
<body>
<nav>
<div class="wrapper">
<ul>
<?php
if(isset($_SESSION["username"]))
{
echo '<button type="submit" name="out" id="logout" class="button"value="Log Out">Log Out</button>';
}
?>
</ul>
</div>
</nav>
<?php
//NO ERRORS AVAILABLE AND THE BUTTON HAS BEEN PUSHED
//ACCESS GRANTED
if (!$show && !$new)
#if(isset($_SESSION["username"]))
{
echo '<div class="output">
<h1 class = "success">'.$msg.'</h1><br>
< div>
<h2 class = "welcomemsg">';
echo $welcome[mt_rand(0, count($welcome)-1)];
echo ', '.$_SESSION["username"].' !<h2>
</div>
</div>';
}
//LOGIN FORM
elseif ($show)
{
echo '
<section class="form-content">
<!--DENIED MESSAGE-->
<div>
<h2 class = "denied">'.$msg.'</h2>
</div>
<h2>Log In</h2>
<br>
<form method="post" action="">
<p>
<label>Username </label>
<input type="text" name="username" placeholder="Username">
</p>
<p>
<label>Password</label>
<input type="password" name="password" placeholder="Password">
</p>
<p>
<button type="submit" name="submit" id="submit" class="button" value="Submit">Log In</button>
<button type="reset" name="reset" id="reset" class="button" value="Clear">Clear</button>
<div>
<span>Don\'t have an account? <button type="submit" name="create" id ="submit" class="button" value ="New">SignUp</abutton></span>
</div>
</p>
</form>
<div class="errors">';
//DISPLAY LOG IN ERROR IF AVAILABLE
if(isset($_GET["error"]))
{
if($_GET["error"] == "emptyinput")
{
echo "<h2>Access Denied</h2><p>Please fill in all fields.</p>";
}
elseif($_GET["error"] == "wronglogin")
{
echo "<h2>Access Denied</h2><p>Oops, it looks like that was incorrect. Try again.</p>";
}
elseif($_GET["error"] == "stmtfailed")
{
echo "<h2>Access Denied</h2><p>Sorry, something went wrong.</p>";
}
}
'</div>
</section>';
}
//SIGN-UP FORM
elseif ($new)
{
echo '
<section>
<h2> New Account </h2>
<div class="newaccount">
<form action="" method="post">
<p>
<label>Username </label>
<input type="text" name="username" placeholder="Username">
</p>
<p>
<label>Password</label>
<input type="password" name="password" placeholder="Password">
</p>
<p>
<button type="submit" name="submit" id="newsubmit" class="button" value="Submit">Sign Up</button>
<button type="reset" name="reset" id="reset" class="button" value="Clear">Clear</button>
<div>
<span>Already have an account? <button type="submit" name="already" id ="submit" class="button" value ="New">Log In</abutton></span>
</div>
</p>
</form>
</div>
<div class="errors">';
//DISPLAY SIGN UP ERROR IF AVAILABLE
if(isset($_GET["error"]))
{
if($_GET["error"] == "emptyinput")
{
echo "<p>Please fill in all fields.</p>";
}
elseif($_GET["error"] == "invalidUid")
{
echo "<p>Choose a valid username consisting of numbers and letters only.</p>";
}
elseif($_GET["error"] == "passwordsdontmatch")
{
echo "</h2><p>Passwords don't match.</p>";
}
elseif($_GET["error"] == "stmtfailed")
{
echo "<p>Sorry, something went wrong, try again.</p>";
}
elseif($_GET["error"] == "usernametaken")
{
echo "<p>Username already taken, please try a different one.</p>";
}
elseif($_GET["error"] == "none")
{
echo "<p>Congratulations, you have been signed up!</p>";
}
}
'</div>
</section>';
}
?>
</body>
</html>
<?php
//FUNCTIONS
//DATABASE CONNECTION INFO
function dbconn()
{
if ($_SERVER['HTTP_HOST'] == 'localhost') //LOCAL
{
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '1550');
define('DB', 'pass_system');
}
else //REMOTE
{
define('HOST', 'localhost');
define('USER', 'mountmer_root');
define('PASS', 'otraIcjwtgbotra');
define('DB', 'mountmer_pass_system');
}
//CONNECT TO DATABASE
#$conn = mysqli_connect(HOST, USER, PASS, DB);
$conn = new mysqli(HOST, USER, PASS, DB);
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
}
function emptyInputSignup($username, $password)
{
$result;
if (empty($username) || empty($password))
{
$result = true;
}
else
{
$result = false;
}
return $result;
}
function invalidUsername($username)
{
$result;
if (!preg_match("/^[a-zA-Z0-9]*$/", $username))
{
$result = true;
}
else
{
$result = false;
}
return $result;
}
function usernameExists($conn, $username)
{
$sqli = "SELECT * FROM user_info WHERE username = ?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqli))
{
header("location: index.php?error=stmtfailed");
$show = true;
$new = false;
#exit();
}
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($resultData))
{
return $row;
}
else
{
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
function hashit($password)
{
$salt1 = 'knridkfva234lke269jg90fnbsdifad23435fvnzmvpedfnk67u5th43rn98bseirvm';
$salt2 = 'zmdkowpqkdjruwqwpir4dbmer093fekrgh9342ojqepfoiewrvneon498w4';
$password = $salt1.$password.$salt2;
$hashedPwd = hash('sha512', $password);
return $hashedPwd;
}
function createUser($conn, $username,$password)
{
$sqli = "INSERT INTO user_info (username, password) VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqli))
{
header("location: index.php?error=stmtfailed");
$show = true;
$new = false;
exit();
}
hashit();
mysqli_stmt_bind_param($stmt, "ss", $username, $hashedPwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
header("location: index.php?error=none");
$show = false;
$new = false;
exit();
}
function emptyInputLogIn($username, $password)
{
$result;
if (empty($username) || empty($password))
{
$result = true;
}
else
{
$result = false;
}
return $result;
}
function loginUser($conn, $username, $password)
{
$usernameExists = usernameExists($conn, $username);
if($usernameExists === false)
{
header("location: index.php?error=wronglogin");
$show = true;
$new = false;
exit();
}
$pwdHashed = $usernameExists["password"];
$checkPwd = password_verify($password, $pwdHashed);
if($checkPwd === false)
{
header("location: index.php?error=wronglogin");
$show = true;
$new = false;
exit();
}
elseif ($checkPwd === true)
{
session_start();
$_SESSION["id"] = $usernameExists["id"];
$_SESSION["username"] = $usernameExists["usersname"];
header("location: index.php?");
$show = false;
$new = false;
exit();
}
}
function logout()
{
session_start();
session_unset();
session_destroy();
header("location: index.php?");
$show = true;
$new = false;
$_GET['error']="";
exit();
}
?>