I have a login form who data are stored in a table users. I also have another table that stores the login date and time.
The table users (id, username, password)
The table user_login (id, user_id, login_date)
The code I tried:
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$name = $_SESSION['username'];
$row=mysqli_fetch_array($results);
$user_id= $row['id'];
$date = date('Y-m-d');
$checkdate= "SELECT id from user_login WHERE user_id='$user_id' AND DATE(login_date)='$date'";
$check=mysqli_query($db, $checkdate)or die(mysqli_error($db));
if(mysqli_num_rows($check)==1){
$updatedate="UPDATE user_login set date= $date where id=$user_id";
mysqli_query($db,$updatedate)or die(mysqli_error($db));
}
else{
$insertdate="INSERT INTO user_login (user_id, login_date) values($user_id, $date)";
mysqli_query($db,$insertdate)or die(mysqli_error($db));
}
// $_SESSION['success'] = "You are now logged in";
header('location: profile.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
The above code just adds date and time every time I login. But I want to save the date only once per day.
Here's one idea.
You could save date into your user_login table and then you can check and compare it
Before inserting into your user login table you would then check it.
Get id of the user from $results.
And check table:
$date=date('Y-m-d');
Select id from user_login where user_id = $user_id and Date(login_date) = $date
If there is a record just update date
$cur_date=date('Y-m-d');
Update user_login set date=$cur_date where id=$user_login_id
else insert one
INSERT INTO user_login (user_id, login_date) values($user_id, $cur_date);
I hope you understand the logic.
I hope you are using mysqli_escape_string in order to prevent from sql injection.
Don't use md5 for password encryption use bcrypt or other secure encryption functions.
here is working version of your code. Don't use it in production.
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$name = $_SESSION['username'];
$row = mysqli_fetch_array($results);
$user_id = $row['id'];
$date = date('Y-m-d');
$datetime = date('Y-m-d H:i:s');
$checkdate = "SELECT id from user_login WHERE user_id='$user_id' AND DATE(login_date)='$date'";
$check = mysqli_query($db, $checkdate) or die(mysqli_error($db));
if (mysqli_num_rows($check) == 1) {
$updatedate = "UPDATE user_login set login_date='$datetime' where user_id=$user_id and DATE(login_date)='$date'" ;
mysqli_query($db, $updatedate) or die(mysqli_error($db));
} else {
$insertdate = "INSERT INTO user_login (user_id, login_date) values($user_id, '$datetime')";
mysqli_query($db, $insertdate) or die(mysqli_error($db));
}
// $_SESSION['success'] = "You are now logged in";
header('location: profile.php');
die;
}else {
array_push($errors, "Wrong username/password combination");
}
}
this is just demonstration.
Related
I got a problem for my profile page in my login system. When I want to update the user's username and email, I can only update one of the two. Look where I putted the points. If I use username it only updates the username and the same goes for the email.
Here is my code:
function updateProfile($db, $errors)
{
$id = $_SESSION['user']['id'];
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$field_check_query = "SELECT * FROM users WHERE username='$username' email='$email'";
$result = mysqli_query($db, $field_check_query);
$field = mysqli_fetch_assoc($result);
// Checks if username is already taken
if ($field) {
if ($field['username'] === $username) {
array_push($errors, "Gebruikersnaam is al reeds ingenomen");
}
// Checks if email is already taken
if ($field['email'] === $email) {
array_push($errors, "E-mailadres is al reeds ingenomen");
}
}
if (count($errors) == 0) {
if (isset($_POST['.......'])) {
$query = "UPDATE users SET username='$username' email='$email' WHERE id=$id";
mysqli_query($db, $query);
header('location: profile.php?profileeditedsuccesfully');
die($query);
}
}
}
Add AND to WHERE in Select:
$field_check_query = "SELECT * FROM users WHERE username='$username' AND email='$email'";
Add comma to separate the pairs in Update.
=$query = "UPDATE users SET username='$username', email='$email' WHERE id=$id";
I made two tables in SQL. first is login table and second is registration table. In login table I inserted a row of user admin and password admin, it works when I am logging in. But now I want to login from registration table. I means if an already registered user want to login how he can did it???
Following is my code, please help me.
when I trying to login as registered user it show me the error "invalid username or password":
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "invalid usernaem or password";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
if (isset($_POST['login'])) { //for the data of registraion table in sql
$username = $_POST['uname'];
$password = $_POST['password'];
$qry = "SELECT * FROM `registration` WHERE `uname`= '$username' OR `email`='$email' AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
}
?>
You need to query the registration table when the login query doesn't find anything.
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
// not an admin, check registration table
$email = $_POST['email'];
$qry = "SELECT * FROM `registration` WHERE (`uname`= '$username' OR `email`='$email') AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
?>
You should also learn to use prepared statements instead of substituting variables into SQL, to protect against SQL-injection. See How can I prevent SQL injection in PHP?. And you should use password_hash() and password_verify() instead of storing plaintext passwords in the database.
I am a newbie and I was trying to create a login system using PHP and Mysql. After finishing registration form and adding few users, I was trying to create a login form. but it always returns false saying my your Your username or password is incorrect!. Below is my code. It will be great if someone could help me. Advance sorry if my doubt is tooo basic :/
<?php
session_start();
include '.\includes\functions\db.php';
?>
<?php
$username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
$password = strtolower(mysqli_real_escape_string($db, $_POST['password']));
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['password'];
echo $hash_pwd;
echo $password;
$hash = password_verify($password, $hash_pwd);
if ($hash ==0) {
header("Location: ./index.php?error=check");
exit();
}else {
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 0) {
echo "Your username or password is incorrect!";
}else {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
}
//header("Location: ./index.php");
}
?>
and my registration page is as follows
<?php
//This Page is for registration of users
?>
<?php
// this php tag is for all includes
include '.\includes\functions\db.php';
?>
<?php
//print isset($_POST["submit"]);
//Getting all details inserted in form
if(isset($_POST["register"])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date('Y-m-d H:i:s');
//Encrypting and Securing recieved data
$username = strtolower(mysqli_real_escape_string($db, $username));
$firstname = strtolower(mysqli_real_escape_string($db, $firstname));
$lastname = strtolower(mysqli_real_escape_string($db, $lastname));
$email = strtolower(mysqli_real_escape_string($db, $email));
$password = strtolower(mysqli_real_escape_string($db, $password));
$encryptedpassword = password_hash($password, PASSWORD_DEFAULT);
//To check duplication of email ids
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db, $sql);
$row = mysqli_num_rows($result);//$row will return count of rows if any duplicate email ids are found
//To check duplication of usernames
$sql2 = "SELECT username FROM users WHERE username='$username'";
$result2 = mysqli_query($db, $sql2);
$row2 = mysqli_num_rows($result2);//$row2 will return count of rows if any duplicate usernames are found
//conditions to check what all duplicates are found
if($row > 0 && $row2 >0){
echo "Sorry...This email id and username is already taken!!!";
} elseif ($row > 0 ) {
echo "Sorry...This email id is already taken!";
} elseif ($row2 > 0) {
echo "Sorry...This Username is already taken!";
}else {
$query = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
if($query){
echo "Thank You! you are now registered.";
}
}
}
?>
The error in my code is because of password = '$hash_pwd' condition in my where clause. When i retried row with given username and later verified password using php, it works as intended. I guess password hashed in php using password_hash() cannot be retrived and verified like encryption. Anyway thanks for all of yours responses
I try to store the logged in attempts in the database, but it's not working. The loginAttempt columns is not updating. Also, I want to count the login attempts and block the user after 3 attempts.
How to fix this?
Here's the script:
session_start();
$loginDate = date("Y-m-d H:i:s");
$Error ="";
$successMessage ="";
if (isset($_POST['submit'])){
if ( !( $_POST['cnumber'] == "" && $_POST['password'] == "")){
$cnumber=$_POST['cnumber'];
$password= sha1($_POST['password']);
$cnumber = filter_var($cnumber, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($cnumber, FILTER_VALIDATE_INT)){
$con=mysqli_connect("localhost","test","password","login");
$result = mysqli_query($con, "SELECT * FROM Users WHERE contractNumber='$cnumber' AND password='$password'");
$data = mysqli_num_rows($result);
if($data==1){
$_SESSION['login_user']=$cnumber;
mysqli_query($con, "INSERT INTO `homecre1_testemailCheck`.`Logs`(`contractNumber`, `lastLogin`) VALUES ('$cnumber', '$loginDate')");
header('Location: profile.php');
} else {
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1 WHERE contractNumber = '$cnumber'");
}
mysqli_close($con);
} else {
$Error ="Invalid Contract Number.";
}
} else {
$Error ="Contract Number or Password is Empty.";
}
Here's my database structure:
Users - table
id -PK
contractNumber
email
password
Logs - table
userId
contractNumber
lastLogin
loginAttempt
Your update query is missing SET and column contarct_number might be wrong: Your query should be like:
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1
WHERE contractNumber = '$cnumber'");
I successfully made the code for logging in...when user logs in, the time of logging in is written in database.
session_start();
$query = mysql_query("SELECT * FROM users");
$result = mysql_fetch_array($query);
if(!empty($_POST['username']) && !empty($_POST['password'])){
$username = ($_POST['username']);
$password = ($_POST['password']);
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND status = '1'");
if(mysql_num_rows($result) == 1) {
mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', 'bkrpan', NOW()) ");
header("Location: admin.php");
exit; }
$result = mysql_query("SELECT username FROM users WHERE username = '$username' AND password = '$password'");
if(mysql_num_rows($result) == 1) {
mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', '$username', NOW()) ");
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header("Location: users.php");
exit; }
echo "Login failed! You will be redirected.";
echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
}
else {
echo "Login failed! You will be redirected.";
echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
}
session_destroy();
but...now I don't know how to make the code for logout.
This is something that I made, but it's not working.
<?php
mysql_connect("localhost", "root", "") or die("cannot connect");
mysql_select_db("zavrsni_rad") or die("cannot select DB");
session_start();
$username = $_SESSION['username'];
$sql = "SELECT * FROM users WHERE username = ".$username." AND password = ".$password;
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1) {
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES (".$username.", NOW() )";
mysql_query($sql_2);
}
session_destroy();
header("location: index.php");
?>
You forgot the single quotes in your queries and you're not getting the value of $password
$sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".$username."', NOW())";
updated for clarity
<?php
session_start();
// check that the session exists first
if(isset($_SESSION['username'])) {
// you should put your db connection in a config.php file and use mysqli or PDO - what you're using is depreciated
mysql_connect("localhost", "root", "") or die("cannot connect");
mysql_select_db("zavrsni_rad") or die("cannot select DB");
// don't think I'd store password in a session...
// also, is username UNIQUE in your database?
// also, also, ALWAYS escape (sanitize) your database input to prevent agains SQL injection
$sql = "SELECT username, password
FROM
users
WHERE
username = '".mysql_real_escape_string($_SESSION['username'])."'
AND
password = '".mysql_real_escape_string($_SESSION['password'])."'";
$result = mysql_query($sql) or die('sql: '.mysql_error());
if(mysql_num_rows($result) > 0) {
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".mysql_real_escape_string($_SESSION['username'])."', NOW())";
mysql_query($sql_2) or die('sql2: '.mysql_error());
session_destroy();
header("location: index.php");
} else {
echo 'There was an error. You have not been logged out.';
}
}