I'm trying to log a user in but I get an error every time I try to verify the password. The username is verified just fine. My password is stored by password_hash in the database. For example, let's say I signup a username 'thisIsAUser' and the password is 'thisIsAUsersPassword'. The hash would be something like: $2y$10$VR5FKZVLP6/43adb1PsGD.bsmrzp15jdftotz6xubDQtypZ1rKEFW. The error would be the else statement of the if(password_verify). Notice that the else statement of the username not matching has a '.' at the end while the password not matching has a '!'.
Logging in script:
<?php
session_start();
$link = mysqli_connect("localhost", "root", "Yuvraj123", "KingOfQuiz");
if(mysqli_connect_error()) {
die("Couldn't connect to the database. try again later.");
}
$query = "SELECT * FROM `users`";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
}
// define variables and set to empty values
$loginSignupButton = "";
$loginUsername = "";
$loginPassword = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginUsername = form_input($_POST["loginUsername"]);
$loginPassword = form_input($_POST["loginPassword"]);
$loginSignupButton = form_input($_POST["loginSignupButton"]);
}
function form_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$loginUsernameError = "";
$loginPasswordError = "";
$error = "";
$loggingInUsername = "";
$unhashedPasswordThingyMajig = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["loginUsername"])) {
$loginUsernameError = "<p style='color: red'>Username is required</p>";
echo $loginUsernameError;
} else {
$loginUsername = form_input($_POST["loginUsername"]);
}
if (empty($_POST["loginPassword"])) {
$loginPasswordError = "<p style='color: red'>Password is required</p>";
echo $loginPasswordError;
} else {
$loginPassword = form_input($_POST["loginPassword"]);
}
if($_POST['loginActive'] == "0") {
$query = "SELECT * FROM users WHERE username = '". mysqli_real_escape_string($link, $_POST['loginUsername'])."' LIMIT 1";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) > 0) {
$error = "<p style='color: red'>That username is already taken.</p>";
echo $error;
} else {
header ('location: signup.php');
}
} elseif($_POST['loginActive'] == "1") {
$sql = "
SELECT *
FROM users
WHERE username = ?
";
$query = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($query, "s", $_POST["loginUsername"]);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
}
}
?>
Form(This is the logging in one, not the signup):
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" id="LoginModalTitle">
<h5 class="modal-title" id="exampleModalLabel LoginModalTitle">Login</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" style="color: white">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="modal-details">
<div class="form-group">
<input type="hidden" id="loginActive" name="loginActive" value="1">
<label for="loginUsername">Username</label>
<input type="text" class="form-control formInput" id="inputUsername" placeholder="Eg: RealKingOfQuiz" name="loginUsername" autocomplete="off" required>
<p><span class="error"><?php echo $loginUsernameError;?></span><p>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" class="form-control formInput" id="inputPassword" name="loginPassword" required autocomplete="on">
<small>Forgot Password?</small>
<p><span class="error"><?php echo $loginPasswordError;?></span></p>
</div>
<p><span class="error"><?php echo $error;?></span></p>
<div class="alert alert-danger" id="loginAlert"></div>
</form>
</div>
<div class="modal-footer">
<a id="toggleLogin">Sign Up?</a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button class="btn btn-success" id="LoginSignUpButton" name="loginSignupButton" form="modal-details" disabled>Login</button>
</div>
</div>
</div>
</div>
If you update the section of code from...
$result = mysqli_stmt_get_result($query);
...to the end of the code block with the below; then it should work.
The problem is that you're reading the password from the wrong result set.
$result = mysqli_stmt_get_result($query);
$dbPassword = mysqli_fetch_assoc($result)["password"] ?? null;
if ($dbPassword) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $dbPassword)) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
You never fetched the row for the user logging in. When you check $row['password'] it's checking the first password in the table, which came from the SELECT * FROM users query at the beginning of the script.
You need to call mysqli_fetch_assoc() after querying for the row for the user.
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
$row = mysqli_fetch_assoc($result);
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
Related
In my code below i have two form section first one is to fetch information from database and second one is verify a record in the database my problem is how do verify a record and redirect to error page or if the input form do not march any record redirect to index page this my code;
<?php
include_once 'init.php';
$error = false;
//check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if(preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if(isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username=$_SESSION["user_name"];
$result=mysqli_query($conn,"select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$id = $row["id"];
$username=$row["username"];
$idd = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"]; $qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
echo "$show";
echo "$balance";
if ($show<$balance) {
if (isset($_POST["verify"])) {
$pass = mysqli_real_escape_string($conn, $_POST["pass"]);
if ($pass != "$username") {
header("location: index.php");
}
elseif ($pass = "$username") {
header("location: ../error.php");
}
}
echo '<form action="#" method="post" name="verify"><input class="text" name="pass" type="password" size="25" /><input class="text" type="submit" name="verify" value="view"></form>';
echo "you cant buy here";
exit();
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table>
<input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div>
</table>
</fieldset>
</form>
in achievement am expected to redirect to error or index page but my code above refress back to first form what are my doing wrong. Big thanks in advance
I have a user system with user registration and user login. on the login page there is a password reset button and on the password rest button the following codes are there but nothing happens when I try to send a password rest link.
CONTROLLER:
function resetPasswordUser()
{
$status = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('login_email','Email','trim|required|valid_email|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->forgotPassword();
}
else
{
$email = $this->input->post('login_email');
if($this->user_model->checkEmailExist($email))
{
$encoded_email = urlencode($email);
$this->load->helper('string');
$data['email'] = $email;
$data['activation_id'] = random_string('alnum',15);
$data['createdDtm'] = date('Y-m-d H:i:s');
$data['agent'] = getBrowserAgent();
$data['client_ip'] = $this->input->ip_address();
$save = $this->user_model->resetPasswordUser($data);
if($save)
{
$data1['reset_link'] = base_url() . "resetPasswordConfirmUser/" . $data['activation_id'] . "/" . $encoded_email;
$userInfo = $this->user_model->getCustomerInfoByEmail($email);
if(!empty($userInfo)){
$data1["username"] = $userInfo[0]->username;
$data1["email"] = $userInfo[0]->email;
$data1["message"] = "Reset Your Password";
}
$sendStatus = resetPasswordEmail($data1);
if($sendStatus){
$status = "send";
setFlashData($status, "Reset password link sent successfully, please check mails.");
} else {
$status = "notsend";
setFlashData($status, "Email has failed, try again.");
}
}
else
{
$status = 'unable';
setFlashData($status, "It seems an error while sending your details, try again.");
}
}
else
{
$status = 'invalid';
setFlashData($status, "This email is not registered with us.");
}
redirect('users/forgotPassword');
}
}
// This function used to reset the password
function resetPasswordConfirmUser($activation_id, $email)
{
// Get email and activation code from URL values at index 3-4
$email = urldecode($email);
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
$data['email'] = $email;
$data['activation_code'] = $activation_id;
if ($is_correct == 1)
{
$this->load->view('templates/header');
$this->load->view('newPassword', $data);
$this->load->view('templates/footer');
}
else
{
redirect('users/login');
}
}
// This function used to create new password
function createPasswordUser()
{
$status = '';
$message = '';
$email = $this->input->post("email");
$activation_id = $this->input->post("activation_code");
$this->load->library('form_validation');
$this->form_validation->set_rules('password','Password','required|max_length[20]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
if($this->form_validation->run() == FALSE)
{
$this->resetPasswordConfirmUser($activation_id, urlencode($email));
}
else
{
$password = $this->input->post('password');
$cpassword = $this->input->post('cpassword');
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
if($is_correct == 1)
{
$this->user_model->createPasswordUser($email, $password);
$status = 'success';
$message = 'Password changed successfully';
}
else
{
$status = 'error';
$message = 'Password changed failed';
}
setFlashData($status, $message);
redirect("users/login");
}
}
MODEL:
function checkEmailExist($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
} else {
return false;
}
}
/**
* This function used to insert reset password data
* #param {array} $data : This is reset password data
* #return {boolean} $result : TRUE/FALSE
*/
function resetPasswordUser($data)
{
$result = $this->db->insert('reset_password', $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
/**
* This function is used to get customer information by email-id for forget password email
* #param string $email : Email id of customer
* #return object $result : Information of customer
*/
function getCustomerInfoByEmail($email)
{
$this->db->select('id, email, username');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('email', $email);
$query = $this->db->get();
return $query->result();
}
/**
* This function used to check correct activation deatails for forget password.
* #param string $email : Email id of user
* #param string $activation_id : This is activation string
*/
function checkActivationDetails($email, $activation_id)
{
$this->db->select('id');
$this->db->from('reset_password');
$this->db->where('email', $email);
$this->db->where('activation_id', $activation_id);
$query = $this->db->get();
return $query->num_rows;
}
// This function used to create new password by reset link
function createPasswordUser($email, $password)
{
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$this->db->update('users', array('password'=>getHashedPassword($password)));
$this->db->delete('reset_password', array('email'=>$email));
}
VIEW:
<div class="row">
<div class="col-md-12">
<?php echo validation_errors('<div class="alert alert-danger alert-dismissable">', ' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>'); ?>
</div>
</div>
<?php
$this->load->helper('form');
$error = $this->session->flashdata('error');
$send = $this->session->flashdata('send');
$notsend = $this->session->flashdata('notsend');
$unable = $this->session->flashdata('unable');
$invalid = $this->session->flashdata('invalid');
if($error)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php }
if($send)
{
?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $send; ?>
</div>
<?php }
if($notsend)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $notsend; ?>
</div>
<?php }
if($unable)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $unable; ?>
</div>
<?php }
if($invalid)
{
?>
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $invalid; ?>
</div>
<?php } ?>
<form action="<?php echo base_url(); ?>users/resetPasswordUser" method="post">
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" name="login_email" required />
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div><!-- /.col -->
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="Submit" />
</div><!-- /.col -->
</div>
</form>
Login<br>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
CONSTANT:
define('EMAIL_FROM', 'xxxx#gmail.com'); // e.g. email#example.com
define('EMAIL_BCC', 'xxxx#gmail.com'); // e.g. email#example.com
define('FROM_NAME', 'CTL '); // Your system name
define('EMAIL_PASS', 'Your email password'); // Your email password
define('PROTOCOL', 'smtp'); // mail, sendmail, smtp
define('SMTP_HOST', 'smtp.gmail.com'); // your smtp host e.g. smtp.gmail.com
define('SMTP_PORT', '25'); // your smtp port e.g. 25, 587
define('SMTP_USER', 'Your smtp user'); // your smtp user
define('SMTP_PASS', 'Your smtp password'); // your smtp password
define('MAIL_PATH', '/usr/sbin/sendmail');
QUESTION UPDATE
I changed my view to load out my errors and what I get is "Email has failed, try again." Error for mail not sent. Thanks
From your comments, it looks like you are using a localhost server. Localhost servers cannot send emails out IIRC. To test sending emails, you have to have a server that has access to the real world (and the feature has to be enabled on that server).
I am working on a class project, but I am stuck a little bit.
I am working on a login form, which authorizes a user to enter a one-time-password that is being sent to the user's email.
So far, the otp and the current time and date are being saved to the database successfully.
I have also managed to send the code to the user's email but once it is sent, the page does not navigate to the form where the user is supposed to enter the one-time-password.
All that works is this part here:
<form method="post" action="">
.
.
.
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
.
.
.
</form>
What could be the problem?? Can someone please help me on this.Thank you.
Here is the html part:
<html>
<head>
<title>Home</title>
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-static-top" role="navigation" style="margin-bottom:20px">
<div class="navbar-header">
<a class="navbar-inverse" href="http://localhost/Dreamweaver/index.php"><img src="img/neza.png" alt="logo"></a>
</div>
<!-- /.navbar-header -->
</nav>
</div>
<div class="container">
<div class="card card-container">
<form class="form-signin" method="post" action="">
<?php
if($success == 1) {
?>
<div class="form-wrap">
<h2>A verification code has been sent to <?php $row["form_email"] ?>. Please enter it below to verify your account.</h2>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<div class="form-group">
<label for="key">Verification Code:</label>
<input type="password" name="otp" id="key" class="form-control">
</div>
<input type="submit" id="btn-login" class="btn btn-custom btn-lg btn-block" name="submit_otp" value="Verify Account">
<h2>Did not receive the verification code?</h2>
<!---- <form id="login-form"> ------>
<input type="submit" id="btn-login" class="btn btn-custom1 btn-lg btn-block" value="Resend Code">
<!----- </form> ----->
</div> <!---/form-wrap----->
<?php
} elseif ($success == 2) {
header("Location: fomu.php");
}else {
?>
<div class="form-top-left">
<h3>Log in</h3>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
<p id="profile-name" class="profile-name-card"></p>
<?php if(!empty($error_message)) { ?>
<div class="error-message"><?php if(isset($error_message)) echo $error_message; ?></div>
<?php } ?>
<span id="reauth-email" class="reauth-email"></span>
<input type="email" id="inputEmail" name="form_email" class="form-control" placeholder="Email address" required autofocus>
<input type="password" name="form_password" id="inputPassword" class="form-control" placeholder="Password" required>
<input class="btn btn-lg btn-primary btn-block btn-signin" type="submit" name="login" value="Sign in">
<div class="text-center">
<a href="wlt_passwordreset.php" class="forgot-password">
Forgot the password?
</a>
</div>
<hr>
<form class="form-signin" action="http://localhost/Dreamweaver/regist.php">
<input type="submit" value="Sign Up" class="btn btn-lg btn-primary btn-block btn-signup">
</form>
<?php
}
?>
</form>
</div><!-- /card-container -->
<div class="container">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="text-centre">
<a class="text-new" href="#">Privacy|</a>
<a class="text-new" href="#">Security|</a>
<a class="text-new" href="#">Fees</a>
</div>
</div> <!---/row--->
</div> <!---/container--->
</div><!-- /container1-->
<!-- jQuery -->
<script src="js/jquery-1.11.1.min.js"></script>
<script src="logwin.js"></script>
<script src="bootstrap.min.js"></script>
<script src="js/mscript.js"></script>
<script src="js/scripts.js"></script>
<script src="js/jquery.backstretch.min.js"></script>
</body>
</html>
Here is the dbtest.php used to INSERT TO the db:
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "myPassword";
private $database = "myDB";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
function numRows($query) {
$result = mysqli_query($this->conn,$query);
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
function updateQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function insertQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function deleteQuery($query) {
$result = mysqli_query($this->conn,$query);
if (!$result) {
die('Invalid query: ' . mysqli_error($this->conn));
} else {
return $result;
}
}
function generate_OTP($length = 8, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789'){
$chars_length = (strlen($chars) - 1);
$string = $chars{rand(0, $chars_length)};
for ($i = 1; $i < $length; $i = strlen($string)){
$r = $chars{rand(0, $chars_length)};
if ($r != $string{$i - 1}) $string .= $r;
}
return $string;
}
function getConn(){
return $this->conn;
}
}
?>
Here is the PHP code that I am referring to:
<?php
session_start();
$success = "";
require_once('dbtest.php');
$db = new DBController();
if(isset($_POST["login"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE
form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
if (!empty($result)){
foreach($result as $row){
//Verify password
if ( $row['form_password'] === crypt( $_POST["form_password"], $row['form_password'] ) ) {
$otp = $db->generate_OTP();
require_once("mail_function.php");
$mail_status = sendOTP($_POST["form_email"],$otp);
if($mail_status == 1) {
$query = "UPDATE registered_users SET `otp` = '" . $otp . "', `is_expired` = 0, `create_at` = '" . date("Y-m-d H:i:s"). "' WHERE form_email = '" . $_POST["form_email"] . "'";
$result = $db->updateQuery($query);
if(!empty($result)){
$current_id = mysqli_insert_id($db->getConn());
if(!empty($current_id)) {
$success = 1;
}
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
}
else {
$error_message = "Email or password is incorrect!";
}
}
if(isset($_POST["submit_otp"])) {
$result = $db->runQuery("SELECT * FROM registered_users WHERE otp='" . $_POST["otp"] . "' AND is_expired!=1 AND NOW() <= DATE_ADD(create_at, INTERVAL 24 HOUR)");
if(!empty($result)) {
$query = "UPDATE registered_users SET `is_expired` = 1 WHERE otp = '" . $_POST["otp"] . "'";
$result = $db->updateQuery($query);
$success = 2;
}else {
$success = 1;
$error_message = "Invalid OTP!";
}
}
?>
Bad syntax: you have the <html> tag inside the <form>, that should not happen. The <html> should only be used once at the beginning to open it and end at the end to close it.
UPDATE:
Also, mysqli_insert_id() expects the link identifier of the last mysqli_connect used. In your code, youre supplying it with $conn, but $conn is not whats being used in the DBController class.
To fix this:
add this method to you DBController class:
function getConn(){
return $this->conn;
}
then change this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($conn);
if (!empty($current_id)) {
$success = 1;
}
}
to this:
$result = $db_handle->insertQuery($query);
if (!empty($result)) {
$current_id = mysqli_insert_id($db_handle->getConn());
if (!empty($current_id)) {
$success = 1;
}
}
UPDATE2:
You asked this "After adding this method function getConn(){ return $this->conn; } I find some errors working with mysqli_fetch_array(). I am using if(!empty($result->num_rows)){while($rowcount = $result->fetch_assoc()){$row['password'];}}"
look at what runQuery() does:
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
it runs your SQL query, then if there are any results, it returns an array $resultset.. The problem is that you are not accounting for empty results. So lets add that, change it to this:
function runQuery($query) {
$resultset = [];
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
return $resultset;
}
Now it will return an empty array, or an array with your results.
And you can call it with:
$result = $db->runQuery("SELECT * FROM registered_users WHERE form_email='" . $_POST["form_email"] . "' AND status = 'active' ");
and use $result like this:
if(!empty($result)){
foreach($result as $row){
echo $row['password'];
}
}
At
"$query = ("SELECT * FROM `accounts` WHERE username = '$username'")or die(mysql_error());"
If I don't add accounts, id then "$_SESSION['userid'] = $row['id'];" wont work but if I do add it then login wont work also accounts is the database and id is inside of it.
<?php
session_start();
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
require '../php/dbConnect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = ("SELECT * FROM `accounts` WHERE username = '$username'")or die(mysql_error());
$response = mysql_query($query);
$row = mysql_fetch_array($response);
if($row['password'] == md5($password))
{
$_SESSION['online'] = true;
$_SESSION['users'] = $username;
$_SESSION['userid'] = $row['id'];
echo '<script type="text/javascript">','redirect();','</script>';
}
else{
echo("Wrong Credentials");
}
?>
<div id="friend-request-title" class="overlay round-edge panel-left">
<label class="w3-text-white "><h2><b>Friend Requests</b></h2></label>
</div>
<div id="friend-request-panel" class="overlay round-edge panel-up">
<?php
require 'php/dbConnect.php';
$query = ("SELECT * FROM `accounts` WHERE `id` <> '".$_SESSION['userid']."'");
$response = mysql_query($query);
while($row = mysql_fetch_assoc($response)) {
echo '
<div class="lesson-section">
<div class="container">
<img id="profile-image" src="img/profile2.png" class="big-circle float" style="margin: 4% 0 0 0;">
</div>
<label id="" class="w3-text-white"><h4><b>You have a new friend request.</b></h4></label>
<label id="" class="w3-text-white">Friend request from '. $row['username'] .'.</label>
<br>
<button id="" class="w3-btn w3-text-white light-overlay border-remove round-edge" style="margin: 2% 2% 0 0;" type="button"><b>Accept</b></button>
<button id="" class="w3-btn w3-text-white light-overlay border-remove round-edge" style="margin: 2% 0 0 0;" type="button"><b>Decline</b></button>
</div>
<hr>
';
}
?>
You have error in this part of your php:
if(isset($_SESSION['users']) != ""){
echo '<script type="text/javascript">','index();','</script>';
}
You should use isset then check if not empty
if(isset($_SESSION['users']) && $_SESSION['users'] != ""){
echo '<script type="text/javascript">','index();','</script>';
}
`
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
if (!preg_match("/^\w+$/",$username)) {
$error = true;
$username_error = "Username cant contain space and special characters";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
$result = mysqli_query($connection, "SELECT * FROM users WHERE username = '" . $username. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
if ($row['id'] == 1) {
header("Location: priv8/ididthis.php");
} else if ($row['id'] >= 1) {
header("Location: index.php");
} else {
$errormsg = "Incorrect username or Password!";
}
can u see what's wrong with my code ? the $errormsg doesn't showing when the username or the password is wrong..
`
<body>
<div class="layout">
<div class="layout-screen">
<div class="app-title">
<h1>Login</h1>
</div>
<div class="layout-form">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div class="control-group">
<input type="text" name="username" class="login-field" value="" placeholder="username" id="login-username">
<label class="login-field-icon fui-user" for="login-username"></label>
</div>
<div class="control-group">
<span><?php if (isset($username_error)) { echo $username_error; } ?></span>
</div>
<div class="control-group">
<input type="password" name="password" class="login-field" value="" placeholder="password" id="login-pass">
<label class="login-field-icon fui-lock" for="login-pass"></label>
</div>
<div class="control-group">
<span><?php if (isset($password_error)) { echo $password_error; } ?></span>
</div>
<div class="control-group">
<input class="btn btn-primary btn-large btn-block" type="submit" name="login" value="Sign in"/>
</div>
</form>
<span><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
<a class="layout-link" href="forgot.php">Lost your password?</a>
</div>
</div>
</div>
The problem is that your error message is inside this block
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else if ($row['id'] >= 1) {...}
else {
$errormsg = "Incorrect username or Password!";
}
}
This means that the error message is never shown because row id will always be 1 or >=1. To fix, move the error message out, like this:
if ($row = mysqli_fetch_array($result)){
if ($row['id'] == 1) {...}
else($row['id'] >= 1) {...}
}
else {
$errormsg = "Incorrect username or Password!";
}