In the following code in crudindex.php if I enter password with length less than 6 characters error message is not showing using the span command.Required pattern is working. But messages using span command is not displaying ex : if i enter length less than 6 in password no error message displays
What is wrong in this code?
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
$error=false;
if (isset($_POST) && (!empty($_POST))){
$uname=mysqli_real_escape_string($con,$_POST["uname"]);
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
$cpwd=mysqli_real_escape_string($con,$_POST["cpwd"]);
$password_error="";
$cpassword_error="";
if(strlen($pwd) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($pwd != $cpwd) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (isset($_POST['register'])) {
# Register-button was clicked
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
if (mysqli_query($con,$createsql1)) {
echo "Insert Successful in Table cruduser";
mysqli_close($con);
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
//include ("crudadd.php");
}
else
{
die(mysqli_error($con));
}
}
if (isset($_POST['login'])) {
# Login-button was clicked
session_start();
$SESSION['suname']=$uname;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin') {
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=$uname&spwd=$pwd");
}
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10">
<input type="text" name="uname" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Username"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10">
<input type="password" name="pwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Password"/>
<span class="error"><?php if (isset($password_error)) echo $password_error;?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10">
<input type="password" name="cpwd" required pattern="^[A-Za-z0-9]+" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
</html>
This is a working example to display your errors and prevent some security problems. I have removed the required pattern from your html. You didn't properly set errors. You can handle errors with php and display them. Plus you didn't use action="path/to/handleform.php".
And your redirect should be in login: header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
There are 3 security problems here:
SQL injection. SOLUTION=> prepared statement
Password saved as plain text. SOLUTION=> password_hash()
Cross-Site Request Forgery (CSRF). SOLUTION=> input hidden with a token
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "", "kkits996_testmysql") or die("Error " . mysqli_error($con));
// Declare array for errors
$error=array();
//-----------------------------------------------------//
//---------------------CSRF PROTECT--------------------//
//-----------------------------------------------------//
//generate a token/
function generateToken( $formName )
{
//secret_key change it
$secretKey ='?#GEskki58668445744!Erpoejsj48';
if ( !session_id() )
{
session_start();
}
$sessionId = session_id();
return hash('sha512', $formName.$sessionId.$secretKey );
}
//check if the token is valid
function checkToken( $token, $formName)
{
return $token === generateToken( $formName );
}
//Separate REGISTER AND LOGIN TO NOT BE CONFUSED//
//-----------------------------------------------------//
//---------------------REGISTRATION--------------------//
//-----------------------------------------------------//
if ( isset($_POST['register']) && checkToken( $_POST['csrf_token'], 'userFromRegistration' ) )
{
//if the username required
if(!preg_match('/^[A-Za-z0-9]+$/',$_POST['uname']))
{
$error['username'] = "Username must have alphanumeric characters ";
}
//if password has less than 6 characters
if(strlen($_POST['pwd']) < 6)
{
$error['password'] = "Password must be minimum of 6 characters";
}
//if password does not match
if($_POST['pwd'] !== $_POST['cpwd'] OR empty($_POST['cpwd']) )
{
$error['passwordmatch'] = "Password and Confirm Password doesn't match";
}
//if empty error array
if( !array_filter($error) )
{
//trim data
$username = trim( $_POST['uname'] );
// Hash you password, never save PASSWORD AS PLAIN TEXT!!!!!!!
// MYSQL! : Allow your storage to expand past 60 characters (VARCHAR 255 would be good)
$password = password_hash( $_POST['pwd'], PASSWORD_DEFAULT);
//if the id is autoincremented leave id
//----------USE PREPARED STATEMENT FOR SQL INJECTION---//
$query = 'INSERT INTO cruduser (username, password) VALUES (?,?)';
$stmt = $con->prepare($query);
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$stmt->close();
$con->close();
//Redirect because we need to consider the post request from crudadd.php
header( 'Location: crudaddusr.php' ) ;
}
}
//-----------------------------------------------------//
//------------------------LOGIN------------------------//
//-----------------------------------------------------//
if (isset($_POST['login']))
{
//what ever you want
//Use password_verify() and session_regenerate_id()
//to compare passwords and to generate a session id to prevent session fixation.
session_start();
$uname = $_POST['uname'];
$pwd = $_POST['pwd'];
//if you don't need it delete it
$SESSION['suname']=$unmane;
$SESSION['spwd']=$pwd;
if ($uname=='admin' && $pwd=='admin')
{
include('crudview.php');
}
else
{
header( "Location: crudeditusr.php?suname=".$uname."&spwd=".$pwd);
}
}
?>
<!--HTMl PART-->
<!DOCTYPE html>
<html>
<head>
<title>"Add records in CRUD Table"</title>
<!-- bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<!-- col-mod-6 col-mod-offset are bootstrap related-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" action="" class="form-horizontal col-mod-6 col-mod-offset-3">
<input type="hidden" name="csrf_token" value="<?php echo generateToken('userFromRegistration'); ?>" required/>
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Username : </label>
<div class="col-sm-10 <?php if( !empty( $error['username'] ) ){ echo 'has-error';} ?> ">
<input type="text" name="uname" class="form-control" id="input1" placeholder="Username"/>
<span class="help-block"><?php if (!empty($error['username'])) echo $error['username'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Password: </label>
<div class="col-sm-10 <?php if( !empty( $error['password'] ) ){ echo 'has-error';} ?>">
<input type="password" name="pwd" class="form-control" id="input1" placeholder="Password"/>
<span class="help-block"><?php if (!empty($error['password'])) echo $error['password'];?></span>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Confirm Password : </label>
<div class="col-sm-10 <?php if( !empty( $error['passwordmatch'] ) ){ echo 'has-error';} ?>">
<input type="password" name="cpwd" class="form-control" id="input1" placeholder="Confirm Password"/>
<span class="help-block"><?php if (!empty($error['passwordmatch'])) echo $error['passwordmatch'];?></span>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
Change this line from this,
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
to this,
$pwd=mysqli_real_escape_string($_POST["pwd"]);
You don't need to add $con to assign your password to another variable but it's better use the direct $_POST variable no need to assign it to another.
if(strlen($_POST["pwd"]) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
Related
I have two files
functions.php
<?php
include 'config.php';
function signup(){
if (isset($_POST['submit'])) {
$uname = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($password == $cpassword) {
$hash = md5($password);
$insert = "INSERT INTO `users`(`user_name`, `email`, `password`) VALUES ('$uname','$email','$hash')";
$result = mysqli_query($con, $insert);
if ($result) {
echo '<script>alert("Your account has been successfully created.")</script>';
}
}
else {
echo '<script>alert("Passwords do not match!")</script>';
}
}
}
?>
signup.php
<?php
include 'functions.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- ===== Iconscout CSS ===== -->
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
<!-- ===== CSS ===== -->
<link rel="stylesheet" href="css/credential.css">
<title>Sing Up</title>
</head>
<body>
<div class="container">
<div class="forms">
<div class="form signup">
<span class="title">Sign Up</span>
<form method="POST" action="functions.php">
<div class="input-field">
<input type="text" name="uname" placeholder="Enter your full name" required>
<i class="uil uil-user"></i>
</div>
<div class="input-field">
<input type="email" name="email" placeholder="Enter your email" required>
<i class="uil uil-envelope icon"></i>
</div>
<div class="input-field">
<input type="password" class="password" name="password" placeholder="Create a password" required>
<i class="uil uil-lock icon"></i>
</div>
<div class="input-field">
<input type="password" class="password" name="cpassword" placeholder="Confirm a password" required>
<i class="uil uil-lock icon"></i>
<i class="uil uil-eye-slash showHidePw"></i>
</div>
<div class="checkbox-text">
<div class="checkbox-content">
<input type="checkbox" id="termCon">
<label for="termCon" class="text">I accepted all Terms and Conditions, Privacy Policy and Cookie Policy</label>
</div>
</div>
<div class="input-field button">
<input type="submit" value="Sign Up" name="submit">
</div>
</form>
<div class="login-signup">
<span class="text">Already have an account?
Login Now
</span>
</div>
</div>
<div class="form login">
<span class="title">Login</span>
<form action="#">
<div class="input-field">
<input type="email" placeholder="Enter your email" required>
<i class="uil uil-envelope icon"></i>
</div>
<div class="input-field">
<input type="password" class="password" placeholder="Enter your password" required>
<i class="uil uil-lock icon"></i>
<i class="uil uil-eye-slash showHidePw"></i>
</div>
<div class="checkbox-text">
<div class="checkbox-content">
<input type="checkbox" id="logCheck">
<label for="logCheck" class="text">Remember me</label>
</div>
Forgot password?
</div>
<div class="input-field button">
<input type="submit" value="Login" name="submit">
</div>
</form>
<div class="login-signup">
<span class="text">Don't have an account?
Signup Now
</span>
</div>
</div>
</div>
</div>
<script src="js/credential.js"></script>
</body>
</html>
I want something like this...
when I click on <input type="submit" of signup the signup() function from functions.php should work. But I don't know how to do it.
If I remove function signup(){} from functions.php and try without function then in url signup.php is replaced by functions.php and page is blank and no data is inserted in mysql localhost.
In 'config.php' file
<?php
$con = mysqli_connect("localhost","root","","get-viewed");
?>
Database name, Table name and field name are perfect I have double checked it.
The form action correctly point to function.php and the webserver execute it.
The result is blank because nothing in function.php get executed.
you defined function signup() but you don't call it
add signup(); as last code line, just before php closing tag ?>
Note 1: you can extract the code from the signup function, since it does not add any advantage.
Note 2: if the php closing tag is the last code line in the file (no html follow) you should omit, it is a good practice to avoid unwanted output.
This is a must once you start to use frameworks, otherwise header errors will popup
Thanks for helping me I have solved my question.
I updated functions.php
<?php
include 'config.php';
function signup() {
$uname = $_POST['uname'];
$email = $_POST['email'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
if($password == $cpassword) {
$hash = password_hash($password, PASSWORD_DEFAULT);
$insert = "INSERT INTO `users`(`user_name`, `email`, `password`) VALUES ('$uname','$email','$hash')";
$result = mysqli_query($con, $insert);
if ($result) {
echo '<script>alert("Your account has been successfully created.")</script>';
}
}
else {
echo '<script>alert("Passwords do not match!");location.replace("signup.php");</script>';
}
}
function login(){
if (isset($_POST['login'])) {
echo '<script>alert("login")</script>';
}
}
if (isset($_POST['signup'])) {
signup();
}
else {
login();
}
Now it is working perfectly as I wanted.
I am new on PHP and I trying to make a simple login system. I want that when i login, if I submit incorrect information system gives validation error and if I submit true info I want to get email or name in profile blade.
Like hello $user!!!
Login page
<html>
<title>Login Form</title>
<body>
<div class="container">
<form class="" method="post">
<label for="email">Enter Your Email</label>
<input type="text" name="email"> <br/>
<label for="password">Enter Your Password</label>
<input type="password" name="pass"><br/>
<input type="submit" value="Login" name="submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
$email=$_POST['email'];
$pass=$_POST['pass'];
if(($email=="cagri#vargonen.com") && ($pass=="1234")){
header()
}
else{
echo "Invalid username/password";
}
}
?>
In login page, I tried;
<?php
$email = $_POST['email'];
$password = $_POST['pass'];
if($email == 'cagri#vargonen.com' && $password == '1234'){
echo "Welcome Çağrı Uğurel";
}
else{
echo "Your email or password incorrect";
}
?>
Can you please help me where is my mistake?
You need to use session_start() to get username or other temp variables.
<?php
session_start();
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$actualuser = "cagri#vargonen.com";
$actualpass = "1234";
if (($email == $actualuser) && ($pass == $actualpass)) {
$_SESSION["username"] = $username;
header("location:somepage.php");
} else {
echo "Username or Password isn't matched.";
}
}
?>
And if login is succeed, username goes to session variable which means you can use that variable during the session.
somepage.php
<?php
session_start();
?>
<html>
<title>User Page</title>
<body>
<p><?php echo $_SESSION["username"];?> </p>
</body>
</html>
I suggest you to use ajax method for kind of these.
EDIT:
Here is real-life example from my previous project.
index.php
<div class="modal fade" id="loginmodal" role="dialog" data-backdrop="static">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1> Giriş yap</h1>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form" method="post" action="index.php">
<div class="form-group">
<label for="usrname"><span class=""></span> Kullanıcı Adı</label>
<input type="text" pattern="[a-z]*"class="form-control" id="usrname" name="username" placeholder="Yetkili veya normal kullanıcı adı giriniz" required>
</div>
<div class="form-group">
<label for="psw"><span class=""></span> Şifre</label>
<input type="password" class="form-control" id="psw" name="password" placeholder="Şifre" required>
</div>
<button type="submit" class="btn btn-success btn-block" name="login"><span class=""></span> Giriş</button>
</form>
</div>
logincheck.php
<?php
if(isset($_POST["login"])){
$username = $_POST["username"];
$password = $_POST["password"];
$query = $db->prepare("select * from users where username=:username AND password=:password");
$query->execute(array(
':username' => $username,
':password' => $password
));
$r = $query->fetch();
$count = $query->rowCount();
if($count > 0 && $r["rank"] > 0) {
$_SESSION["username"] = $username;
$_SESSION["rank"] = $r["rank"];
header("location:project.php");
}
}
?>
userpage.php
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#"> <?php echo $_SESSION["username"];?> <span class="caret">
</span></a>
<ul class="dropdown-menu">
<li>Çıkış yap</li>
</ul>
</li>
</ul>
Hope, this is help!
Add semicolon here header();
<html>
<title>Login Form</title>
<body>
<div class="container">
<form class="" method="post">
<label for="email">Enter Your Email</label>
<input type="text" name="email"> <br/>
<label for="password">Enter Your Password</label>
<input type="password" name="pass"><br/>
<input type="submit" value="Login" name="submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
session_start();
$email=$_POST['email'];
$pass=$_POST['pass'];
if(($email=="cagri#vargonen.com") && ($pass=="1234")){
$_SESSION['user'] = array('email'=>$email);
echo 'Hello '.$_SESSION['user']['email'].'...!';
}
else{
echo "Invalid username/password";
}
}
?>
Bellow is part of the code from register.php
if($_SERVER['REQUEST_METHOD'] == "POST") {
/* running some checks of an input*/
if(sizeof($errorArray)==0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php',true,303);
}
else{
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php',true,303);
}
}
Logic is simple -- if an errorArray is empty redirect to a success page, else redirect to register.php itself. To avoid form resubmission i tried to put post variables into session variable, so the user doesn't have to fill form again in case of error.
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
$_SESSION['post'] = null;
$_SESSION['errorArray'] = null;
}
?>
This part of a code is executed later in register.php but it doesen't gives me the result I want. Somehow the variables are sett to null before the loop above is executed (??!). I have found a solution with get method that includes microtime in url passed to header , but it seams to me that there is more elegant solution that does not every time adds new values to a session variable.
Is there some way around this?
edit :
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// array to hold all the errors of input
$errorArray = [];
$emailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$nameRegex = '/^[a-z0-9][a-z0-9_]*[a-z0-9]$/';
$passwordRegex = '/^[a-z0-9][-a-z0-9_!##$?]*[a-z0-9]$/';
$email = $_POST['email'];
if (empty($email)) {
array_push($errorArray, "E-mail field required");
} else {
if (!preg_match($emailRegex, $email)) array_push($errorArray, 'Invalid email');
}
$name = $_POST['name'];
if (empty($name)) {
array_push($errorArray, "Name field required");
} else {
if (!preg_match($nameRegex, $name)) array_push($errorArray, 'Invalid name');
}
$password = $_POST['password'];
$passwordR = $_POST['passwordR'];
if (empty($passwordR) || empty($password)) {
array_push($errorArray, 'Password fields required');
} else if (!preg_match($passwordRegex, $password)) {
array_push($errorArray, 'Invalid password');
} else {
if ($password !== $passwordR) {
array_push($errorArray, 'Password inputs are not the same');
}
}
if (sizeof($errorArray) == 0) {
// redirecting to avoid form resubmission
$_SESSION['registered'] = true;
header('location: success.php', true, 303);
} else {
$_SESSION['post']['email'] = $_POST['email'];
$_SESSION['post']['name'] = $_POST['name'];
$_SESSION['errorArray'] = $errorArray;
header('location: register.php', true, 303);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/maincss.css" type="text/css">
<meta name="viewport" content="width = device-width, initial-scale = 1, user - scalable = no">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed">
<div class="container">
Home
<ul class="navbar-brand col-xs-5"><?= (isset($username)) ? 'Welcome ' . $username : ''; ?></ul>
Login
Register
</div>
</nav>
<div class="container">
<form class="form-signin" action="register.php" method="post">
<h2 class="form-signin-heading text-center text-capitalize">Registration form</h2>
<!-- I have purposely excluded required attribute from inputs and set type="text"
for an email so all the checks could be done on server side -->
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="email" class="sr-only">Email address</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email address"
value="<?= (isset($_SESSION['post']['email'])) ? $_SESSION['post']['email'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="name" class="sr-only">Name</label>
<input type="text" id="name" name="name" class="form-control" placeholder="Name"
value="<?= (isset($_SESSION['post']['name'])) ? $_SESSION['post']['name'] : ''; ?>" autofocus>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row center-block">
<div class="col-xs-4"></div>
<div class="col-xs-4">
<label for="passwordR" class="sr-only">Repeat Password</label>
<input type="password" id="passwordR" name="passwordR" class="form-control"
placeholder="Repeat Password">
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div class="row">
<div class="col-xs-4"></div>
<div class="col-xs-4 center-block">
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</div>
<div class="col-xs-4"></div>
</div>
<br>
<div>
<?php
if (isset($_SESSION['errorArray'])) {
if (sizeof($_SESSION['errorArray']) != 0) {
echo '<div class="alert alert-danger" role="alert">
<h4>There were errors in Your input:</h4>';
foreach ($_SESSION['errorArray'] as $item) {
echo $item . '<br>';
}
}
// $_SESSION['post'] = null;
// $_SESSION['errorArray'] = null;
}
?>
</div>
</form>
</body>
</html>
I've reset my database and on registration, we added random salt to hashes, and the registration script worked fine, we could create accounts and accounts with the same password and they had different hashes, but our login script is broken, not logging in users, saying their password is incorrect.
No idea why- we have spent the last 2 hours trying to fix it. We have used PHP error checkers(https://phpcodechecker.com/), nothing was wrong.
We are running an old version PHP(5.6) and MySQL and can't currently change.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
$res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
$row=mysql_fetch_array($res);
$row['userSalt']=$salt1;
$row['userSalt2']=$salt2;
// if there's no error, continue to login
if (!$error) {
$passwordHash = hash('sha256', $salt1 . $password . $salt2); // password hashing using SHA256
//$res=mysql_query("SELECT userId, userEmail, userPass, userSalt, userSalt2 FROM users WHERE userName='$name'");
//$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be 1 row
if( $count == 1 && $row['userPass']==$passwordHash ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#overallhead").load("overall_header.php");
$("#overallfoot").load("overall_footer.html");
});
</script>
<style>
body {
color: Thistle;
}
</style>
<div id="overallhead"></div>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Creature Paradise</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="container">
<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<div class="col-md-12">
<div class="form-group">
<h2 class="">Login</h2>
</div>
<div class="form-group">
<hr />
</div>
<?php
if ( isset($errMSG) ) {
?>
<div class="form-group">
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="name" name="name" class="form-control" placeholder="Your Username" value="<?php echo $name; ?>" maxlength="40" />
</div>
<span class="text-danger"><?php echo $nameError; ?></span>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
</div>
<div class="form-group">
<hr />
</div>
<div class="form-group">
Don't have an account? Sign up here!
</div>
</div>
</form>
</div>
</div>
<div id="overallfoot"></div>
</body>
</html>
<?php ob_end_flush(); ?>
Have you do hashing on registration page, too? Because $row['userPass'] will never equal $passwordHash if you have not registration a new account with new hash applied
I am redirecting a user to a page named "forgot_pass" in such a way
"forgot_pass.php?code='$code'&username='$hidden_username'>".
But when user clicks on link for redirection the url seems like this
http://localhost/Validation/forgot_pass.php?code=
and there is no any page displayed.
The variables passed in url have values as i have already checked it. But they are not displaying when sent in url.
Help me in solving this issue.
reset.php
<?php
ini_set("display_errors", TRUE);
require_once './include/db_connection.php';
$pass = $_POST['pass'];
$pass1 = $_POST['pass1'];
$code = $_GET['code'];
$hidden_username = $_POST['username'];
if($pass == $pass1)
{
echo 'Password Changed !';
}
else
{
echo "Passowrd must match
<a href='forgot_pass.php?code='$code'&username='$hidden_username'>Try Again</a>
";
}
forgot_pass.php
<?php
ini_set("display_errors", TRUE);
require_once './include/db_connection.php';
if(isset($_GET['code']))
{
$get_code = (isset($_GET['code'])? $_GET['code'] : null);
$get_username =(isset($_GET['username']) ? $_GET['username'] : null);
$match_code = mysqli_query($link, "select * from signup where username='$get_username'");
if(mysqli_num_rows($match_code) > 0)
{
while($row = mysqli_fetch_assoc($match_code))
{
$db_username = $row['username'];
$db_code = $row['paareset'];
}
}
if($get_username == $db_username && $get_code == $db_code)
{ ?>
<html>
<head>
<meta charset="UTF-8">
<title>Change Password</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-body">
<div class="text-center">
<h3><i class="fa fa-pencil fa-4x"></i></h3>
<h2 class="text-center">New Password?</h2>
<div class="panel-body">
<form class="form" method="post"
action= "reset_pass.php?code=<?php echo $get_code ?>"
<fieldset>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil color-blue"></i></span>
<input name="pass" placeholder="New Password" class="form-control" type="password" required="">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil color-blue"></i></span>
<input name="pass1" placeholder="Re-type Password" class="form-control" type="password" required="">
<input type="hidden" name="username" value="<?php echo $db_username ?>">
</div>
</div>
<div class="form-group">
<input class="btn btn-lg btn-primary btn-block" name="send" value="Change Password" type="submit">
</div>
<div class="form-group">
<span style="color: red"><?php if(isset($message['mail'])) {echo $message['mail']; } ?></span>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
}
} // End if (isset['code'])
if(!isset($_GET['code']))
{
?>
<html>
<head>
</head>
<body>
// Here i am displaying another form that gets email address and sends email
</body>
</html>
<?php
}
Remove single-quotes around the arguments, you are using them to delimit the URL so don't use them inside the URL (or at least escape them) :
echo "Password must match <a href='forgot_pass.php?code=$code&username=$hidden_username'>Try Again</a>";
Try with this way
echo "Passowrd must match
Try Again"
you have mismatch in columns
try to change your code to
echo "Passowrd must match
<a href='forgot_pass.php?code=".$code."&username=".$hidden_username".'>Try Again</a>
"
Please check if your filenames are correct.
You named: reset.php and forgot_pass.php
In forgot_pass.php your action goes towards reset_pass.php
remove single quote
"forgot_pass.php?code=$code&username=$hidden_username>"