I have created a change password page where the 1st is condition if ($newpassword == 0) is working properly but else part is not working if I omit the 1st if condition the other conditions are working properly but with every refresh password field also taking blank save in DB table. The code is given below for help. Thank you in advance.
<?php
include('session.php');
include('config.php');
//error_reporting(0);
$error = ''; // Variable To Store Error Message
$newpassword = $_POST['npassword'];
$confirmnewpassword = $_POST['cpassword'];
if ($newpassword == 0) {
$error = "Set a New Password!";
} else {
if ($newpassword == $confirmnewpassword) {
$sql = mysqli_query($con, "UPDATE t_login SET password='$newpassword'");
} else if ($sql) {
$error = "Congratulations You have successfully changed your password!";
} else {
$error = "New Password and Confirm Password do not match. Try again!";
}
}
?>
As i've commented your conditons are wrong.
if ($newpassword == $confirmnewpassword) { //If you enter here you can t reach other conditions
$sql = mysqli_query($con, "UPDATE t_login SET password='$newpassword'");
} else if ($sql) {
$error = "Congratulations You have successfully changed your password!";
} else {
$error = "New Password and Confirm Password do not match. Try again!";
}
You should do that
if ($newpassword == $confirmnewpassword) {
//HERE THERE IS AN SQL INJECTION
$sql = mysqli_query($con, "UPDATE t_login SET password='$newpassword'");
if ($sql) {
$error = "Congratulations You have successfully changed your password!";
} else {
$error = "Mysql query error !";
}
} else {
$error = "New Password and Confirm Password do not match. Try again!";
}
You should use prepared statement or at least escape parameters because if your user type a ' inside his password your code will fail !
EDIT I ve forgot to tell that your query change the password for every records in your table, maybe you forgot to use a WHERE.
Hope this helps
Most of these comments don't directly have much to do with your question, but some remarks:
<?php
include('session.php');
include('config.php');
//error_reporting(0);
Please uncomment this, to get some valuable warnings!
$error = ''; // Variable To Store Error Message
$newpassword = $_POST['npassword'];
$confirmnewpassword = $_POST['cpassword'];
As you do not know if these are set, I would check (also to avoid a warning) if it actually exists, so something like $newpassword = $_POST['npassword'] ?? '';
if ($newpassword == 0) {
You are checking if it is "sort of" (the double is does type juggling for you) equal to 0. That's quite vague. I would check if it is a valid password or not, for instance !== ''. This wil work really well with previous tip.
$error = "Set a New Password!";
} else {
if ($newpassword == $confirmnewpassword) {
You can safely use === here.
$sql = mysqli_query($con, "UPDATE t_login SET password='$newpassword'");
You probably want a WHERE statement in here, because this updates all rows in your table.
} else if ($sql) {
As you defined the $sql in your if above, and this is in an else, it will never be true(ish) here. This is the major bug in the code
$error = "Congratulations You have successfully changed your password!";
} else {
$error = "New Password and Confirm Password do not match. Try again!";
}
}
?>
If you don't mix HTML and php, please omit the end-php tag.
Related
I want to display the first name of the person that logged in to my website. This is the code of my login.php file which is included in one page of my website.
<?php
$connect = mysql_connect("localhost","root","") or die("Error");
mysql_select_db("jpnv_db") or die("Couldn't find db");
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
$names = mysql_query("SELECT contactFirstName FROM customers WHERE `username`='$username'");
if (empty($username)) {
$errors[] = 'Please fill in your username. Click here to try again.';
}
if (empty($password)) {
$errors[] = 'Please fill in your password. Click here to try again.';
}
if ($errors==true) {
foreach ($errors as $error) {
echo $error.'<br />';
}
} else {
if (mysql_num_rows($query)==true) {
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}
}
?>
This is the result when the password is incorrect:
This is the result when I actually log in succesfully:
As you can see in my code, it should actually show the name of the person who logged in in the top bar. But however, it is completely empty. What am I doing wrong here?
You never fetch the results from the query and you need to ask for the correct column name from the query:
if (mysql_num_rows($query)==true) {
$name = mysql_fetch_assoc($names)
echo $name['contactFirstName']; // change the column name here
} else {...
You need to prevent SQL Injection or someone will make all of your data disappear.
Please, stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO.
function login() {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) || empty($password))
{
echo "You haven't filled username/password";
// redirect code here//
}
else
{
$query = mysqli_query("$con, SELECT * FROM customers WHERE `username`='$username' AND `password`='$password'");
if ($query && mysqli_num_rows($query)!=0) {
$row =mysqli_fetch_assoc($query);
echo "Customer name is : " . $row['customers']; // you need to specify columns in between ' ' to get it. Change it based on your need.
}
}
}
Note : You should migrate to Mysqli or PDO. $con in the code is the variable that holds db connection.
check this line of code. You are not identifying $name variable.
else {
//$names variable
if $(mysql_num_rows($query)==true) {
$names = mysql_fetch_all($query);
echo $names['customers'];
} else {
echo 'Your username and/or password are incorrect. Click here to try again.';
}
}
I'm having some problems with this login script, I've already had someone else look it over for me and we cannot seem to figure out what the issue is.
What's happening is when a user tries to login, if the the username is correct it will check if the password is correct and if the password is correct it updates the last access date and redirects like it is supposed to. However if the username is correct and the password is incorrect. It should empty out the password, and let the user know the password they entered is incorrect.
What actually happens when the password is incorrect, is it is skipping to the outermost else statement, and emptying out the username and password and saying there is an issue...whether or not the username entered is correct (regardless of whether or not the password is right).
I have no idea what is happening here, and hopefully someone can help me shed some light on it.
Thank you!
$selectUser = pg_prepare($dbConnection, "selectuser_query", 'SELECT * FROM users WHERE user_id = $1 AND password = $2');
<?php
$error = "";
$username_error = "";
$password_error = "";
if($_SERVER["REQUEST_METHOD"] == "GET")
{
$login = "";
$password = "";
}
else if($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = trim($_POST["login"]);
$password = trim($_POST["password"]);
if(!isset($login) || $login == "")
{
$username_error = "You must enter your user name to login!";
}
if (!isset($password) || $password == "")
{
$password_error = "You must enter your password to login!";
}
if(($error == "") && ($password_error == "") && ($username_error == ""))
{
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password"));
if($login == pg_fetch_result($selectUser, "user_id"))
{
if($password == pg_fetch_result($selectUser, "password"))
{
$date = date("n-j-Y");
$updateDateAccess = pg_execute($dbConnection, "updatedate_query", array("'$date'", "$login"));
header('Location: ./welcome.php');
}
else
{
$password = "";
$error = "The password is incorrect. Please try again.";
}
}
else
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
}
}
?>
Your problem is your query:
SELECT * FROM users WHERE user_id = $1 AND password = $2
It checks both the username and password, which results in no records being returned if the password is incorrect. Thus, the next if condition isn't satisfied:
$selectUser = pg_execute($dbConnection, "selectuser_query", array("$login", "$password")); // no records
if($login == pg_fetch_result($selectUser, "user_id")) // not satisfied, because there are no records
{
// ...
}
else // this runs
{
$login = "";
$password = "";
$error = "The username/password is incorrect. Please try again.";
}
What you want to do is run a query that retrieves the (salted and hashed) password for a given username, then check the password in your application logic.
Also, as others have pointed out in the comments, this is not a good way to store passwords or respond to incorrect info. It looks like the passwords are in plain text, but they should be hashed and salted. Also, you should not tell the user which part of the information was incorrect; otherwise, you let an attacker determine valid usernames and then focus on brute-forcing those.
Hi i have a registration system, and it works well and save to database, I have a problem in checking on the database for the username if already exists. My script on checking database is wrong. Can someone help me on this? Below is my code
<?php
if(empty($_POST['username'])){
$username_error = "Please Input Username";
}else{
if( 6 > mb_strlen($_POST['username']) || 20 < mb_strlen($_POST['username'])){
$username_error = "username must be at least 6 characters.";
}else{
$sql = "SELECT
members.username
FROM
members
WHERE username = $username";
$res = mysql_query($sql);
if(mysql_num_rows($res)){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
}
}
?>
problem is only in the else statement
Change :
$sql = "SELECT
members.username
FROM
members
WHERE username = $username";
To:
$sql = "SELECT
members.username
FROM
members
WHERE username = '".mysql_real_escape_string($username)."'";
$users =mysql_query($sql);
if(mysql_num_rows($users )){
$username_exists = "Username is already taken.";
}{
$username = $_POST['username'];
}
Have in mind, you need to escape your user name to avoid SQL injection! And avoid using mysql_ functions!
Before you read on; this is prone to SQL injection, and I'd love to point you to PDO.
Change your SQL statement to treat $username as a string;
SELECT members.username
FROM members
WHERE username = '$username'
Then remove the following line,
mysql_query($sql);
And finally change your if() { } condition to;
if(mysql_num_rows(mysql_query($sql))>0){
I have tried to help you with this code. Pay attention to comments. I have done more then just, answer your question: there are a bit changed logic, added sanitize of $username...
<?php
// at first let's define this variables (just for any case)
$username_error = null;
$username_exists = null;
// get username
$username = $_POST['username'];
// let's check it
if (empty($username)) {
$username_error = "Please Input Username";
// don't know in what context you use this code
// so here you need to return from function or exit
return;
}
// ... and sanitize
$username = filter_var($username, FILTER_SANITIZE_SPECIAL_CHARS); // just for example
// actually, I use active record, so can't suggest 100%-security way
// check lenght
if (mb_strlen($username) < 6 || mb_strlen($username) > 20) {
$username_error = "username must be at least 6 characters.";
// also let's exit or return
return;
}
// and now let's check it in DB
$sql = "SELECT
members.username
FROM
members
WHERE username = '$username'";
// !!! pay attention!!!
$result = mysql_query($sql); // we need append this mysql result to some variable
if (mysql_num_rows($result) > 0) { // and here we check num_rows of that result, not just tring with query!
$username_exists = "Username is already taken.";
// also let's exit or return
return;
}
// if we are in here we have sanitized $username, that's not in use.
// Enjoy!
var qc=document.forms["regform"]["email"].value;
if(qc!='') {
alert('in');
$.ajax({
url: 'search.php',
data: "check_qc=" + qc,
async:false,
success: function(response) {
if(response==1)
{
alert('Already Exists');
return false;
}
}
});
}
Now, in search.php file
$qc = $_GET['check_qc'];
$sel="select * from register where email='".$qc."'";
$res= mysql_query($sel);
$co= mysql_num_rows($res);
// echo $co;
if(count($co)>0)
echo "1";
else
echo "0";
if(mysql_num_rows($sql)>0){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
Although you should be using PDO or something else for sanitization.
Correction:
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)){
$username_exists = "Username is already taken.";
}else{
$username = $_POST['username'];
}
I have been using a tutorial for a registration and log in page. Everything is perfect except when a user inputs an incorrect password.
If no password is entered then the stated error is displayed fine.
If the correct password is entered it logs them in.
If the incorrect password is entered it goes to a blank page?!
I want an incorrect password to display a message just like when the wrong username is entered. I've included my entire login.php code:
include('db.php');
if(!isset($_POST['login'])) {
include('form.php');
} else {
if(isset($_POST['user'])&&$_POST['user']==""||!isset($_POST['user'])) {
$error[] = "Username Field can't be left blank";
$usererror = "1";
}
if(!isset($usererror)) {
$user = mysql_real_escape_string($_POST['user']);
$sql = "SELECT * FROM users WHERE user = '$user'";
if(mysql_num_rows(mysql_query($sql))=="0") {
$error[] = "Can't find a user with this username";
}
}
if(isset($_POST['pass'])&&$_POST['pass']==""||!isset($_POST['pass'])) {
$error[] = "password Field can't be left blank";
}
if(isset($error)) {
if(is_array($error)) {
echo "<div class=\"error\"><span>please check the errors and refill the form<span><br/>";
foreach ($error as $ers) {
echo "<span>".$ers."</span><br/>";
}
echo "</div>";
include('form.php');
}
}
if(!isset($error)) {
$suser=mysql_real_escape_string($_POST['user']);
$spass=md5($_POST['pass']);//for secure passwords
$find = "SELECT * FROM users WHERE user = '$suser' AND password = '$spass'";
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())) {
session_start();
$_SESSION['username'] = $suser;
header("Location: loggedin.php");
} else {
echo "<div class=\"warning\"><span>Some Error occured durring processing your data</div>";
}
}
}
if(mysql_num_rows(mysql_query($find))=="1"or die(mysql_error())){
If wrong password is entered, mysql_num_rows(mysql_query($find)) is 0 so it results in die(mysql_error()). But since there is no mysql_error(), you see a blank page.
Try this
$result = mysql_query($find) or die(mysql_error());
if (mysql_num_rows($result) == 1) {
// proceed
} else {
// authentication failed
}
EDIT: This is just for illustration purpose only. Use MySQLi or PDO when dealing with MySQL.
The code is little bit confusing for me, consider using this code.
<?php
include('db.php');
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['user']);
$password = md5($_POST['pass']);
if(empty($username) || empty($password)) {
echo "Empty username or password.";
} else {
mysql_query("SELECT * FROM `users` WHERE `user` = '$user' AND `password.md5` = '$password'");
if(mysql_num_rows() == 1) {
// login successfull
session_start();
$_SESSION['username'] = $username;
header("Location: loggedin.php");
} else {
echo "Invalid username or password.";
}
}
} else {
include ('form.php');
}
?>
if(isset($_POST['login'])) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
if(empty($username) || empty($password)) {
$error = 1;
$error_message = 'Please fill in all the required fields.';
} else {
get_login_name($username, $password);
//The commented line works...
//$query = mysql_query("SELECT /* user_logged true, page login */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1");
}
if(mysql_num_rows(get_login_name($username, $password)) == 0) {
echo get_login_name($username, $password);
$error = 1;
$error_message = 'Incorrect username or password.';
} elseif ($error == 0) {
//Other stuff....
}
}
Function:
function get_login_name($password, $username) {
global $myDB;
global $config;
$query = "SELECT /* page == login, functions.php */username, password FROM members WHERE username = '".$username."' AND password = '".sha1($password)."' LIMIT 1";
$result = $myDB->Execute($query) or die(GetDbError($myDB->ErrorMsg()));
return $result;
}
How properly check if username or password incorrect ? (part if(mysql_num_rows(g.....)
In my opinion something wrong i have done ir function get_login_name with return and checking. By the way, using adodb.
EDIT:
After all i decided a bit test it, so, let's leave function as it now and let's check username and password part:
if (!is_null(get_login_name($password, $username))) {
echo get_login_name($password, $username);
$error = 1;
$error_message = 'Incorrect username or password.';
}
If username or password incorrect ir gives me:
username,password which mean result doesn't found at all (no user, if user correct gives same)
Ok, let's enter valid user and pass, and it gaves:
username,password zero,0a706ce75f3bc195c8ed7be5a21d3766abb0d384
What's wrong ?
Essentially, if get_login_name has a return, that means the query returned a match for username and password which means the combination is correct, otherwise, no result means there's no match so you could say either username or password is incorrect (because they don't exist or one of them is wrong). If $Result has a value using get_login_name would likely to be just:
if (!is_null(get_login_name($password, $username)))
// correct
else
// incorrect
Play around with it and see the results.
Ech, after testing managed it to work :)
That seems this part fails :/
if (!is_null(get_login_name($password, $username)))
So, hole code:
if (!$myDB->Affected_Rows()) {
//if(mysql_num_rows($query) == 0) {
$error = 1;
$error_message = 'Incorrect username or password.';
}
What i have ? Just changed it to:
if (!$myDB->Affected_Rows()) {
Thank you all guys who tryed help.