I am creating reset password system, Iam done with all parts accept last step where updating password and email in users table.
actually where it doesn't update.lol
it says update succes and redirecting to login but doesn't update pasword.
I echoed all steps to see if values are empty it shows all full.
This is my form:
$selector = $_GET["selector"];
$validator = $_GET["validator"];
if(empty($selector) || empty($validator)){
echo "Could not validate request";
}else{
if(ctype_xdigit($selector) !== false && ctype_xdigit($validator) !== false){
?>
<form action="reset-password.inc.php" method="post">
<input type="hidden" name="selector" value="<?php echo $selector; ?>">
<input type="hidden" name="validator" value="<?php echo $validator; ?>">
<input type="password" name="password" placeholder="Yeni şifre girin...">
<input type="password" name="confirm_password" placeholder="Şifre tekrar...">
<input type="submit" name="reset-password-submit" value="Submit">
<a class="btn btn-link" href="welcome.php">Cancel</a>
</form>
<?php
}
}
And this is the codes in submit page:
if(isset($_POST["reset-password-submit"])){
$selector = $_POST["selector"];
$validator = $_POST["validator"];
$password = $_POST["password"];
$confirm_password = $_POST["confirm_password"];
$currentDate = date("U");
if(empty($password) && empty($confirm_password)){
header("Location: create-new-password.php?newpwd=empty");
exit();
}elseif($password != $confirm_password){
header("Location: create-new-password.php?newpwd=passwords-not-same");
exit();
}else{
$sql = "SELECT * FROM pwdreset WHERE pwdResetSelector = :pwdResetSelector AND pwdResetToken = :pwdResetToken AND pwdResetExpires >= :pwdResetExpires";
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":pwdResetSelector", $selector, PDO::PARAM_STR);
$stmt->bindParam(":pwdResetToken", $validator, PDO::PARAM_STR);
$stmt->bindParam(":pwdResetExpires", $currentDate, PDO::PARAM_STR);
if($stmt->execute()){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($selector !== $row['pwdResetSelector']){
header("Location: create-new-password.php?newpwd=wrongUrlParameters");
exit();
}elseif($validator !== $row['pwdResetToken']){
header("Location: create-new-password.php?newpwd=wrongUrlParameters");
exit();
}else{
$tokenEmail = $row["pwdResetEmail"];
// CHECK IF EMPTY PASS AND EMAIL AND DO UPDATE
if(empty($password) && empty($tokenEmail)){
$sql = "UPDATE users SET password = :password WHERE email=:email";
if($stmt3 = $pdo->prepare($sql)){
$newpwdhash = password_hash($password, PASSWORD_DEFAULT);
$stmt3->bindParam(":password", $newpwdhash, PDO::PARAM_STR);
$stmt3->bindParam(":email", $tokenEmail, PDO::PARAM_STR);
if($stmt3->execute()){
// DELETE FROM PWDRESET TABLE
$sql = "DELETE FROM pwdReset WHERE pwdResetEmail=:pwdResetEmail";
if($stmt4 = $pdo->prepare($sql)){
$stmt4->bindParam(":pwdResetEmail", $tokenEmail, PDO::PARAM_STR);
$stmt4->execute();
header("Location: login.php?newpwd=success");
exit();
}else{
header("Location: create-new-password.php?newpwd=somethingWentWrong");
exit();
}
}else{
echo "Couldnt execute stmt 3";
exit();
}
}else{
echo "error";
exit();
}
}else{
echo "AN ERROR HAPPEND WHILE QUERY STMT 3";
exit();
}
}
}else{
echo "Couldnt execute sql 1";
exit();
}
}else{
echo "prepare sql didnt work 1";
exit();
}
}
}else{
echo "something went wrong";
exit();
}
Related
I hate to be the new guy asking can you fix this code, or at least tell me how, but I'm going on a month here trying to figure out why it doesn't work, and if its not obvious I've only been coding since February, so my knowledge is very limited, I have been studying several different courses, and have had success coding a similar script with md5 and in many other less secure ways, but I do not want to put a site online with those scripts.
My problem is I can sign up a user password,username,etc, is stored and hashed properly in database, but when i try to log in as that user i cannot figure out why I'm not getting the password properly verified, I'm always directed to the pwd error line.
I'm working most the time during the week and have little time to tinker with this except on the weekends, but this is the fourth weekend now and id really love to get this fixed without having to rewrite the whole thing. I am really wanting to have something like this using prepared statements, i have compared each statement to the php manual and it looks valid to me, i have gone over it again & again & again, trying to find what is wrong, but everything i check seems like it should work. I'm lost.
Here are the files that should be required for someone to see whats going on. . .
signup script
<?php
require "header.php";
?>
<main>
<div class="wrapper-main">
<section class="section-default">
<h1>Signup</h1>
<form class="form-signup" action="includes/signup.inc.php" method="POST">
<input type="text" name="mailuid" placeholder="Username">
<input type="email" name="mail" placeholder="E-mail">
<input type="password" name="pwd" placeholder="Password">
<input type="password" name="pwd-repeat" placeholder="Repeat Password">
<button type="submit" name="signup-submit">Signup</button>
</form>
</section>
</div>
</main>
<?php
require "footer.php";
?>
<?php
if (isset($_POST['signup-submit'])) {
require 'dbh.inc.php';
$username = $_POST['mailuid'];
$email = $_POST['mail'];
$password = $_POST['pwd'];
$passwordRepeat = $_POST['pwd-repeat'];
/// checks that user filled all feilds
if (empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfeilds&uid=".$username."&mail=".$email); //error msgs to user
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username)) {
header("Location: ../signup.php?error=invalidmail&uid");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?error=invalidmail&uid=".$username);
exit();
}
else if (!preg_match("/^[a-zA-Z0-9]*$/",$username)) {
header("Location: ..signup.php?error=imvalidui&mail=".$email);
exit();
}
else if ($password !== $passwordRepeat) {
header("Location: ../signup.php?error=passwordcheck&id=".$username."&mail=".$email);
exit();
}
else {
// checks for matching users in db
$sql = "SELECT * FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultcheck = mysqli_stmt_num_rows($stmt);
if ($resultcheck > 0) {
header("Location: ../signup.php?error=usertaken=".$username);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt,$sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username,$email,$hashedPwd);
mysqli_stmt_execute($stmt);
header("Location: ../index.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../signup.php");
exit();
}
Now the login script
<?php
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdcheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../index.php?login=success");
exit();
}
else {
header("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header("location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header("Location: ../index.php");
exit();
}
You place the username in uidUsers and the email in emailUsers field, but then you read it with "SELECT * FROM users WHERE uidUsers=?;" and bind it to $mailuid.
I think it should be "SELECT * FROM users WHERE emailUsers=?;" instead.
Also make sure that the database field holding the password hash is of type varchar(255), shorter fields can truncate the password hash.
thanks Paul T. you were right on, the tip about the error log was a big help, I was not aware of that. As i said i have only just begun to learn all this a short time ago. The sad thing is I was taught in a tutorial to write the password_verify statement that way. I changed the part in question to . . .
<?php
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['pwdUsers'])) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../index.php?login=success");
exit();
}
else {
header("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header("location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header("Location: ../index.php");
exit();
}
And now it all finally works as intended. Are there any outstanding security issues with any of this?
I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>
I created a signup form and once a user has successfully signed up, it should redirect to home.php. But instead, it's being redirected to index.php. Everything else works (please see the code below). I could see that a user was added to my database, and that the status of the profile picture is 1.
<?php
if (isset($_POST['submitSignup'])) {
include_once 'dbh.inc.php';
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['passwordS'];
if (empty($first) || empty($last) || empty($email) || empty($username) || empty($password)) {
header("Location: ../signup.php?signup=empty"); exit();}
else{
if (!preg_match("/^[A-Za-z\s'-]{2,50}$/", $first) || !preg_match("/^[A-Za-z\s'-]{2,50}$/", $last)) {
header("Location: ../signup.php?signup=flnameinvalid&email=$email&username=$username"); exit();}
else{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../signup.php?signup=emailinvalid&first=$first&last=$last&username=$username"); exit();}
else{
$mysql = "SELECT * FROM users WHERE user_username='$username';";
$result = mysqli_query($conn, $mysql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header("Location: ../signup.php?signup=unametaken&first=$first&last=$last&email=$email"); exit();}
else{
if (strlen($password) < 8) {
header("Location: ../signup.php?signup=strlen&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
if (!preg_match("#[0-9]+#", $password)) {
header("Location: ../signup.php?signup=num&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
if (!preg_match("#[A-Z]+#", $password)) {
header("Location: ../signup.php?signup=cap&first=$first&last=$last&email=$email&username=$username"); exit();}
else{
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (user_first, user_last, user_email, user_username, user_password)
VALUES (?, ?, ?, ?, ?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare ($stmt, $sql)) {
echo "SQL error!";}
else{
mysqli_stmt_bind_param ($stmt, "sssss", $first, $last, $email, $username, $hashedPwd);
mysqli_stmt_execute ($stmt);
$sql3 = "SELECT * FROM users WHERE user_username='$username' AND user_first='$first';";
$result = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userid = $row['id'];
$sql4 = "INSERT INTO profileimg (userid, status) VALUES ($userid, 1);";
mysqli_query($conn, $sql4);
}
}
else{ echo "There are no users!";}
}
header("Location: ../home.php?signup=success"); exit();
}
}
}
}
}
}
}
}
else{header("Location: ../signup.php?signup=error");}
The header function doesn't work even if I placed it after the mysqli_execute($stmt).
I tried creating a user-defined function instead, but it is still not working.
It was working last night when I haven't added the last if and else statement yet, the one with $sql3.
========= UPDATED ==========
Somehow, I was able to identify that the redirect it is following is the header function within the last else statement of my home.php. Here's the code
<div class="sideright">
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$sqlImg = "SELECT * FROM profileimg where userid='$id'";
$resultImg = mysqli_query($conn, $sqlImg);
while ($rowImg = mysqli_fetch_assoc($resultImg)) {
echo "<div>";
if ($rowImg['status'] == 0) {
echo "<img src='uploads/profile".$id.".$fileActualExt'".mt_rand()." height='200' width='200'>";}
else{
echo "<img src='uploads/defaultprofilepicture.jpg' height='200' width='200'>";}
echo $row['user_username'];
echo "</div>";
}
}
}
else{
echo "Sorry, an error occurred.";}
if (isset($_SESSION['key'])) {
echo
'<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" value="Change Profile Picture">
<button type="submit" name="submitFile"> Go </button>
</form>';
echo
'<form action="includes/logout.inc.php" method="POST">
<button type="submit" name="submitLogout"> Log Out </button>
</form>';
}
else{
header("Location: index.php");}
I still haven't fixed it, please help me find out where I went wrong.
try
echo "<script type=\"text/javascript\">".
"window.location='signup.php?signup=error';".
"</script>";
You may try this, it's Working for me.
Replace this code to Your Header Location
<script type=\"text/javascript\">
window.location.href='home.php';
</script>
I have a profile page, function for the edit and a check function for the edit.
profile page:
if (isset($_POST['edit']) && $_POST['edit'] === 'Edit') {
$errorMsgs = $user->validateUpdate($_POST);
if (empty($errorMsgs)) {
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$user->updateProfile($username,$email,$id);
echo 'edited';
exit;
}
foreach ($errorMsgs as $msg) {
echo '<li>'. $msg. '</li>';
}
}
while ($row = mysqli_fetch_assoc($result)) {
?>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
Username<br>
<input type="text" name="username" value="<?php echo $row['username']; ?>" /><br>
Email<br>
<input type="text" name="email" value="<?php echo $row['email']; ?>" /><br>
<input name="edit" type="submit" value="Edit"/>
</form>
<?php }
?>
Update function:
function updateProfile($username,$email,$id){
$con = new Core();
$con->connect();
$username = trim(strtolower($username));
$username = str_replace(' ', '', $username);
$sql = 'UPDATE users SET username = ?, email = ? where id = ?';
if ($stmt = $con->myconn->prepare($sql))
{
$stmt->bind_param('ssi', $username, $email, $id);
$stmt->execute();
$stmt->close();
}
else{
die("errormessage: " . $con->myconn->error);
}
}
Check function:
function validateUpdate(array $userDetails)
{
$con = new Core();
$con->connect();
$errmsg_arr = array();
foreach($userDetails as $key => $value) {
if (empty($value)) {
$errmsg_arr[] = ucwords($key) . " field is required";
}
}
if (!empty($userDetails['edit'])) {
if (!empty($userDetails['email']) && !filter_var($userDetails['email'], FILTER_VALIDATE_EMAIL)) {
$errmsg_arr[] = "the provided email is not a valid email address";
}
$sqlu = "SELECT username FROM users WHERE username = ?";
if($stmt = $con->myconn->prepare($sqlu)){
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Username already exists!";
$stmt->close();
}
$sqle = "SELECT email FROM users WHERE email = ?";
if($stmt = $con->myconn->prepare($sqle)){
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
}
if($stmt->fetch() > 0){
$errmsg_arr[] = "Email already exists!";
$stmt->close();
}
}
return $errmsg_arr;
}
Everything works perfect. But there's a flaw in this check.
Someone goes to their profile.
The person tries to edit details, edits it all: code echo's "succesfully edited".
But if the person tries to edit Email only instead of all details, gets the error message that the "Username value" already exists.
Now my question: How would I let it not check on the username value if it isn't edited? Or email value?
Thanks in advance!
you would exclude the user that's logged in from the query. While doing the login you would save the users id in a session variable. You can use this variable for preventing the queries from checking against the user itself
$sqlu = "SELECT username FROM users WHERE username = ? AND id != '".$_SESSION['user_id']."'";
$sqle = "SELECT email FROM users WHERE email = ? AND id != '".$_SESSION['user_id']."'";
That should fix your issue! More info on session variables
I am learning to make website with some video tutorials based on mysqli. I came to know that using prepared statements are more secure and I am trying to create a login system. Here is what I have done so far.
This code helps me login success fully.
<form action ="" method="post">
User Name:<br/>
<input type='text' name='username' />
<br/><br/>
Password:<br/>
<input type='password' name='password' />
<br/><br/>
<input type='submit' name='submit' value='login'>
</form>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{$_SESSION['Logged'] = 1;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();
?>
But I also need to check if the user have not activated or have been banned or deactivated. So I made another code.
And here is the code I made
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$stmt = $con->prepare("SELECT username, password FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
$result=$con->query($stmt);
$row=$result->fetch_array(MYSQLI_ASSOC);
$user_id= $row['user_id'];
$status = $row['status'];
if($status=='d'){
echo "YOUR account has been DEACTIVATED.";
}else{
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->free_result();
$stmt->close();
}
else
{
}
$con->close();
?>
When I use this I get the following errors
Warning: mysqli::query() expects parameter 1 to be string, object given in F:\XAMPP\htdocs\login\login.php on line 33
Fatal error: Call to a member function fetch_array() on a non-object in F:\XAMPP\htdocs\login\login.php on line 34
I have database table columns
user_id,
username,
password (md5),
user_level,
status.
Under user_level I have the following
a = admin
m = member
Under status
a = activated
n = not activated
d = deactivated
b = banned
While logging in I need to check if the user status and if it is activated it should move to index page or if it is d it should show the user has been deactivated and likewise for others.
How to do it in prepared statements?
And I have this connect.php in all page
?php
//error_reporting(0);
'session_start';
$con = new mysqli('localhost', 'username', 'password', 'database');
if($con->connect_errno > 0){
die('Sorry, We\'re experiencing some connection problems.');
}
?>
I think you need to take a look into how mysqli_ works. This should get you in the right direction.
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$user_id = 0;
$status = ""
$stmt = $con->prepare("SELECT user_id, username, password, status FROM users WHERE username=? AND password=? LIMIT 1");
$stmt->bind_param('ss', $username, $password);
$stmt->execute();
$stmt->bind_result($user_id, $username, $password, $status);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
if($stmt->fetch()) //fetching the contents of the row
{
if ($status == 'd') {
echo "YOUR account has been DEACTIVATED.";
exit();
} else {
$_SESSION['Logged'] = 1;
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;
echo 'Success!';
exit();
}
}
}
else {
echo "INVALID USERNAME/PASSWORD Combination!";
}
$stmt->close();
}
else
{
}
$con->close();