I'm attempting to create a page whereby users are able to change their password, but having trouble with my sql statment, can someone tell me where i'm going wrong? here's the code;
<?php
session_start();
include_once("home_start.php");
require_once("functions.php");
require_once("db_connect.php");
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$newpassword = trim($_POST['newpassword']);
$repeatnewpassword = trim($_POST['repeatnewpassword']);
if ($username && $password){
session_start();
require_once("db_connect.php");
mysqli_select_db($db_server, $db_database) or die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$pass = $_POST[‘password’];
$salt = "$salt1$string$salt2";
$hashpass = md5($pass . $salt);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
if($row = mysqli_fetch_array($result)){
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username && salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
$querychange = mysql_query("UPDATE users SET password='$newpassword' WHERE
username='$username'") or die(mysql_error());
} else {
$message = "<h1>Incorrect password!</h1>";
}
mysqli_free_result($result);
require_once("db_close.php");
} else {
$message = "<h1>Please enter a valid username/password</h1>";
}
//home_start/end only required if submitting to a separate page
//include_once("home_start.php");
echo $message;
}
?>
<h1>Change Password</h1>
<form id="register" action='password.php' method='POST'>
Username: <input type='text' name='username'><br />
Current Password: <input type='password' name='password'><br />
New Password: <input type='password' name='newpassword'><br />
Repeat New Password: <input type='password' name='repeatnewpassword'><br />
<input type='submit' name='submit' value='Login'> <br />
</form>
<?php include_once("home_close.php"); ?>
When you are comparing the password for verification, I found that you have used salt over your given password. Which means you have already a salted(or encrypted) password in db.
salt($password)==$db_password
But when you are storing the new password in to db, I didn't see you encrypt(or salt) on it.
UPDATE users SET password='$newpassword'...
So, when you are doing login using the new password, you'll never get it matched!
Related
This question already has answers here:
How to check username and password matches the database values
(3 answers)
Closed last month.
So I was following this youtube guide on setting up a log in system with PHP, and I ran into some trouble when I got to the authentication part where the user's username and password are check against the database. Even when a correct username and password that are in the database are submitted, the if statement in login.php echos "Incorrect username or password!"
dbh.php <= this connects to the local databse
<?php
$conn = mysqli_connect("localhost", "admin", "admin", "user_list");
if(!$conn) {
die("Connection failed");
}
?>
sign_up.php <= takes user account info and enters it into the database
<?php
include 'dbh.php';
$first = $_POST['first'];
$last = $_POST['last'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO user (first, last, uid, pwd)
VALUES ('$first', '$last', '$uid', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: login_page.html");
?>
login.php <= this takes user input and checks to see if a matching pair is in the databse
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "Your username or password is incorrect!";
} else {
echo "You are logged in!";
}
?>
login_page.html (not full page just login/signup forms)
<div class="content">
<form action="login.php">
<input type="text" name="uid" placeholder="Username"><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit">LOG IN</button>
<br><br><br>
</form>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Firstname"><br>
<input type="text" name="last" placeholder="Lastname"><br>
<input type="text" name="uid" placeholder="Username"><br>
<input type="password" name="pwd" placeholder="Password"><br>
<button type="submit">SIGN UP</button>
</form>
</div>
Try to use prepared statements in order to avoid SQL injection!
By way of example in your login.php
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "connect_error" . $mysqli->connect_error;
}
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$result = $mysqli->prepare('SELECT * FROM user WHERE uid=? AND pwd=?');
$result->bind_param("is", $uid, $pwd);
$result->execute();
$result->bind_result($col1,$col2);
$result->fetch();
$is_valid_profile = ($col1!=null) ? 'You are logged in!' : 'Your username or password is incorrect!';
echo $is_valid_profile;
$result->close();
http://php.net/manual/en/mysqli.prepare.php
You can do like this. This might work
<?php
include 'dbh.php';
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
echo "You are logged in!";
} else {
echo "Your username or password is incorrect!";
}
?>
You can remove this sign and it will work
OR
this is also a solution
if (mysqli_num_rows($result)) {
echo "You are logged in!";
} else {
echo "Your username or password is incorrect!";
}
I am attempting to make my first login system. For some reason when I try to get the password from my database it doesn't give a value? I'm not sure what I'm doing wrong. The error is somewhere between $sql and $db_password.
#LFlare Im not sure what the DESC users thing is. Here is a picture of the table, I wasn't sure how you wanted it. http://i.imgur.com/WkZV7IZ.png
Thanks!
<?php
session_start();
if (isset($_POST['login'])) {
include_once("db.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username = '$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
//echo "Password: $password";
//echo "DB Password: $db_password";
if ($password == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php");
} else {
echo "You didn't enter the correct details!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login.php" method="post" enctype="multipart/form-data">
<input placeholder="Username" name="username" type="text" autofocus>
<input placeholder="Password" name="password" type="password">
<input name="login" type="submit" value="Login">
</form>
</body>
</html>
Your PHP
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
include_once("db.php");
$username = mysqli_real_escape_string($sqlcon, $_POST['username']);
$password = mysqli_real_escape_string($sqlcon, $_POST['password']);
// If you want to make sure username is alphanumeric, you can do
// $username = preg_replace('/[^a-zA-Z0-9]/', '', mysqli_real_escape_string($sqlcon, $_POST['username']));
// Do not use these, mysqli_real_escape_string is enough to prevent injection attacks. Furthermore, you may be compromising user security by remove special characters in passwords.
// $username = strip_tags($_POST['username']);
// $password = strip_tags($_POST['password']);
// $username = stripslashes($username);
// $password = stripslashes($password);
// $password = md5($password); This is very susceptibile to rainbow table attacks, do something like a loop
for ($i = 0; $i < 1000; $i ++) {
$password = md5($password . $username); // Looping the md5 a thousand times and salting it with the username is good practice too.U
}
$userQuery = "SELECT * FROM users WHERE username = '" . $username . "' LIMIT 1";
$user = mysqli_query($sqlcon, $userQuery);
if (mysqli_num_rows($user) > 0) { // If user exists,
$user = mysqli_fetch_assoc($user); // mysqli_fetch_arrays put values into $user[0], $user[1], etc.
$id = $user['id'];
$databasepass = $user['password'];
if ($password === $databasepass) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: index.php");
} else {
echo "Password is incorrect";
}
} else {
echo "Username does not exist";
}
} else {
echo "Username or Password not filled in";
}
echo $password;
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login.php" method="post" enctype="multipart/form-data">
<input placeholder="Username" name="username" type="text" autofocus>
<input placeholder="Password" name="password" type="password">
<input name="login" type="submit" value="Login">
</form>
</body>
</html>
Your db.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database = "users";
$sqlcon = mysqli_connect($host, $user, $pass, $database);
if (mysqli_connect_errno()) {
die ("MySQL Database Connection Error");
}
?>
You have your $db, and $sql backwards in mysqli_query.
$query = mysqli_query($sql, $db);
http://php.net/manual/en/function.mysql-query.php
Also, try avoid using md5, and use PHP's password_hash, http://php.net/manual/en/function.password-hash.php.
Currently, if the DB gets exploited, it's vulnerable to rainbow table attacks.
I am working on login system. But, i cannot log in. I have set my database table.
login.php
<?php
session_start();
if(isset($_POST['login'])) {
include_once("db.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: av_pocetna.html");
} else {
echo "You didn't enter the correct details!";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1 style="font-family: Tahoma;">Login</h1>
<form action="login.php" method="post" enctype="multipart/form-data">
<input placeholder="Username" name="username" type="text" autofocus>
<input placeholder="Password" name="password" type="password">
<input name="login" type="submit" value="Login">
</form>
</body>
</html>
and this is db.php
<? php
$db=mysqli_connect('192.168.1.113:8080','root','hidden','av');
?>
connent of users table
id
username
password
Edit Edit
Copy Copy
Delete Delete
1
a
0cc175b9c0f1b6a831c399e269772661
Your form code look right. Just change like below your login.php code:-
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('host-name','user-name','password','database-name');
if($conn){
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
if($query){
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: av_pocetna.html");
} else {
echo "You didn't enter the correct details!";
}
}else{
echo "query not executed because".mysqli_error($conn);
}
}
}else{
echo "db connection error".mysqli_connect_error();
}
?>
Note:- i have added connection code here only,so change the credentials there. And use this same code to check working or not?
Also if you are working on your local then change ip address to localhost and check. If it will work then it will work with include("db.php") too.I mean to say try with $conn = mysqli_connect('localhost','root','aleksandar','av');
Here is the working login.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','root','aleksandar','av');
$db = new mysqli('localhost','root','aleksandar','av');
if($conn){
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
if($query){
$row = mysqli_fetch_array($query);
$id = $row['id'];
$db_password = $row['password'];
if($password == $db_password) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
header("Location: av_pocetna.html");
} else {
echo "You didn't enter the correct details!";
}
}else{
echo "query not executed because".mysqli_error($conn);
}
}
}else{
echo "db connection error".mysqli_connect_error();
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1 style="font-family: Tahoma;">Login</h1>
<form action="login.php" method="post" enctype="multipart/form-data">
<input placeholder="Username" name="username" type="text" autofocus>
<input placeholder="Password" name="password" type="password">
<input name="login" type="submit" value="Login">
</form>
</body>
</html>
Oh Okay.
Lets try debugging one step at a time then.
In your db.php file, use this:
// Connecting to mysql database
$db = new mysqli('192.168.1.113:8080','root','hidden','av');
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
If you get any error, please dump it here for debugging.
Updated.
// Connecting to mysql database
$db = new mysqli('localhost','root','hidden','av');
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
A part of a website I am making gives the option to the user to change their password. I have configured this code and it works fine.
I now want to add a form to the same page, that gives the user an option to change their USERNAME instead. (Individually, so they change their username but don't change the password).
Do I need to repeat the exact same following code and paste it beneath it, obviously adapting particular words to be for the username not password, or is there a way I can ADD to the existing code so that its one single processing code? How do I do this? So for example the first line:
if ($submit == 'Change Password') {,
in my head in English language, I'd like the code to say IF 'change password' OR the 'change username' button is submitted... do the following code etc.
//processing code
<?php
require_once('checklog.php');
require_once('functions.php');
// Grab the form data
$submit = trim($_POST['submit']);
$password = trim($_POST['password']);
$newpassword = trim($_POST['newpassword']);
$repeatpassword = trim($_POST['repeatpassword']);
// Create some variables to hold output data
$message = '';
// Start to use PHP session
session_start();
if ($submit == 'Change Password') {
include_once('connect.php');
mysqli_select_db($db_server, $db_database) or die("Couldn't find db");
//clean the input now that we have a db connection
$password = clean_string($db_server, $password);
$newpassword = clean_string($db_server, $newpassword);
$username = $_SESSION['username'];
$repeatpassword = clean_string($db_server, $repeatpassword);
if ($password && $newpassword) {
if ($repeatpassword == $newpassword) {
if (strlen($newpassword) > 25 || strlen($newpassword) < 6) {
$message = "Password must be 6-25 characters long";
} else {
// check whether username exists
$password = salt($password);
$query = "SELECT username FROM users WHERE username='$username' and password='$password'";
$result = mysqli_query($db_server, $query);
//if theres a result change password to new password
if ($row = mysqli_fetch_array($result)) {
$newpassword = salt($newpassword);
$repeatpassword = salt($repeatpassword);
//update password
$query = "UPDATE users SET password='$newpassword' WHERE username='$username'";
mysqli_query($db_server, $query) or die("Update failed. " . mysqli_error($db_server));
$message = "<strong>Password change successful!</strong>";
} else {
$message = "User account not found.";
}
mysqli_free_result($result);
}
} else {
$message = "Password must match";
}
} else {
$message = "Please enter all fields";
}
include_once('db_close.php');
}
include_once('header_logged.php');
?>
// the forms to change the password or username
!--change password form -->
To change your Password:
<form method="post" action="changepassword.php">
Current password: <input type='password' name='password'>
<br>
<br>
New Password: <input type='password' name='newpassword'>
<br>
<br>
Repeat New Password: <input type='password' name='repeatpassword'>
<input type='submit' name='submit' value='Change Password'>
<input type='reset' name='reset' value='Reset'>
</form>
<p><strong><?php
echo $message;
?></strong></p>
<!--change username form -->
To change your Username:
<form method="post" action="changepassword.php">
Current Username: <input type='username' name='username'>
<br>
<br>
New Username: <input type='username' name='newusername'>
<br>
<br>
Repeat New Username: <input type='username' name='repeatusername'>
<input type='submit' name='change' value='Change Username'>
<input type='reset' name='reset' value='Reset'>
</form>
Thanks for any help, very much appreciated.
use this:
if(isset($_POST['submit']) || isset($_POST['change'])){
//write your code here
}
I've created a login + register site. The register page works fine, login too except that when I have to write in my password I have to write in the encrypted version, the md5...
I've done in register page so that their password gets encrypted. How can I make in login page so that they dont need to write their md5 password, just their normal one?
The register.php looks like:
<?
$reg = #$_POST['reg'];
//declaring variables to prevent errors
$fn = ""; //First Name
$ln = ""; //Last Name
$un = ""; //Username
$em = ""; //Email
$em2 = ""; //Email 2
$pswd = ""; //Password
$pswd2 = ""; // Password 2
$d = ""; // Sign up Date
$u_check = ""; // Check if username exists
//registration form
$fn = strip_tags(#$_POST['fname']);
$ln = strip_tags(#$_POST['lname']);
$un = strip_tags(#$_POST['username']);
$em = strip_tags(#$_POST['email']);
$em2 = strip_tags(#$_POST['email2']);
$pswd = strip_tags(#$_POST['password']);
$pswd2 = strip_tags(#$_POST['password2']);
$d = date("Y-m-d"); // Year - Month - Day
if ($reg) {
if ($em==$em2) {
// Check if user already exists
$u_check = mysql_query("SELECT username FROM users WHERE username='$un'");
// Count the amount of rows where username = $un
$check = mysql_num_rows($u_check);
if ($check == 0) {
//check all of the fields have been filed in
if ($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2) {
// check that passwords match
if ($pswd==$pswd2) {
// check the maximum length of username/first name/last name does not exceed 25 characters
if (strlen($un)>25||strlen($fn)>25||strlen($ln)>25) {
echo "The maximum limit for username/first name/last name is 25 characters!";
}
else
{
// check the maximum length of password does not exceed 25 characters and is not less than 5 characters
if (strlen($pswd)>30||strlen($pswd)<5) {
echo "Your password must be between 5 and 30 characters long!";
}
else
{
//encrypt password and password 2 using md5 before sending to database
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = mysql_query("INSERT INTO users VALUES ('','$un','$fn','$ln','$em','$pswd','$d','0')");
die("<h2>Welcome to InstaWord!</h2>Login to your account to get started ...");
}
}
}
else {
echo "Your passwords don't match!";
}
}
else
{
echo "Please fill in all of the fields";
}
}
else
{
echo "Username already taken ...";
}
}
else {
echo "Your E-mails don't match!";
}
}
?>
<table class="homepageTable">
<tr>
<td width="60%" valign="top">
<h2>Share your texts!</h2>
<img src="img/animation.gif" width="930">
</td>
<td width="40%" valign="top">
<h2>Sign up</h2>
<form action="#" method="post">
<input type="text" size="25" name="fname" placeholder="First Name" value="<? echo $fn; ?>">
<input type="text" size="25" name="lname" placeholder="Last Name" value="<? echo $ln; ?>">
<input type="text" size="25" name="username" placeholder="Username" value="<? echo $un; ?>">
<input type="text" size="25" name="email" placeholder="Email" value="<? echo $em; ?>">
<input type="text" size="25" name="email2" placeholder="Repeat Email" value="<? echo $em2; ?>">
<input type="password" size="25" name="password" placeholder="Password">
<input type="password" size="25" name="password2" placeholder="Repeat Password"> <br />
<input type="submit" name="reg" value="Sign Up!">
</form>
</td>
</tr>
</table>
</body>
</html>
And the login.php looks like this:
<?php
session_start();
//This displays your login form
function index(){
echo "<form action='?act=login' method='post'>"
."Username: <input type='text' name='username' size='30'><br>"
."Password: <input type='password' name='password' size='30'><br>"
."<input type='submit' value='Login'>"
."</form>";
}
//This function will find and checks if your data is correct
function login(){
//Collect your info from login form
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
//Connecting to database
$connect = mysql_connect("myserver", "username", "password");
if(!$connect){
die(mysql_error());
}
//Selecting database
$select_db = mysql_select_db("database_name", $connect);
if(!$select_db){
die(mysql_error());
}
//Find if entered data is correct
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = mysql_fetch_array($result);
$id = $row['id'];
$select_user = mysql_query("SELECT * FROM users WHERE id='$id'");
$row2 = mysql_fetch_array($select_user);
$user = $row2['username'];
if($username != $user){
die("Username is wrong!");
}
$pass_check = mysql_query("SELECT * FROM users WHERE username='$username' AND id='$id'");
$row3 = mysql_fetch_array($pass_check);
$email = $row3['email'];
$select_pass = mysql_query("SELECT * FROM users WHERE username='$username' AND id='$id' AND email='$email'");
$row4 = mysql_fetch_array($select_pass);
$real_password = $row4['password'];
if($password != $real_password){
die("Your password is wrong!");
}
//Now if everything is correct let's finish his/her/its login
session_register("username", $username);
session_register("password", $password);
echo "Welcome, ".$username." please continue on our <a href=index.php>Index</a>";
}
switch($act){
default;
index();
break;
case "login";
login();
break;
}
?>
Please help me fix this...
You are not using md5 to check while login....
Use $password = md5($_REQUEST['password']); In your login function().
This will take the normal password and check it with encrypted version in database and then will successfully log the user in.
Hope this helps.
You should not apply a strip_tags() to the $_POST['password'], just feed the incoming value to the password hashing function.
To protect your user's passwords, you need to do better than md5 hash the passwords.
You need
a better hashing algorithm: BCrypt hash
add a random salt value
The good news is that you can just use a drop-in library and use that: PHPass
require('PasswordHash.php');
$pwdHasher = new PasswordHash(8, FALSE);
// $hash is what you would store in your database
$hash = $pwdHasher->HashPassword( $_POST['password'] );
// $hash would be the $hashed stored in your database for this user
$checked = $pwdHasher->CheckPassword($_POST['password'], $hash);
if ($checked) {
echo 'password correct';
} else {
echo 'wrong credentials';
}
Encrypt the input password with md5() when you pass the details into sql query while checking correct login details.
$password_encrypt = md5($password);
$result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password_encrypt '");