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'");
Related
For my website I need to be able to get an ID from a database after someone logged in. I already figured out how to put the variables from the login page into a session but I cant figure out how to write a code that gets an ID from a database and turns it into a session variable.
session_start();
include( "connection.php" );
if(isset($_GET['action']) && ($_GET['action'] == "login")){
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$pass = mysqli_real_escape_string($conn, md5( $_POST['pass'] . "90qdjka*#"));
$QUERY = "SELECT * FROM users WHERE username = '$name' AND password = '$pass' AND enabled = 1";
$EXEC = mysqli_query($conn, $QUERY );
if(mysqli_num_rows($EXEC)==0){
die( 'Login niet geldig! Opnieuw inloggen' );
}else{
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
$QUERY = "UPDATE users SET lastlogin=NOW() WHERE username = '$name' AND password = '$pass'";
mysqli_query($conn, $QUERY);
}
}
?>
else{
if (mysqli_num_rows($EXEC) > 0) {
while($row = mysqli_fetch_assoc($EXEC)) {
$_SESSION['id'] = $row["id"];
}
}
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
if your query returns only one result then while loop will run only one time but if your query returns more than one record then the last record's id will be stored in your session variable
In $row["id"], id is the column name of the table, if you are selecting all columns from your table and if your users table has columns like name, username, password then you can access it using $row["name"], $row["username"], $row["password"]
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.
I have a column in a table (users) called admin and its datatype is boolean. Two users are set to "true"
My objective is when those two log in, they have acess to the back office, but so far the code isn't working:
<?php
session_start();
$error="";
$successMessage="";
if ($_POST){
if(!isset($_POST["salada"]) || $_POST["salada"]===""){
$error = "PHP: An email is required <br>";
}
if(!isset($_POST["arroz"]) || $_POST["arroz"]===""){
$error .= "PHP: A password is required";
}
if ($error !=""){
$error = '<div class="error-login">'.$error.'</div>';
}else {
require("MGconfig.php");
$email = mysqli_real_escape_string($connection, $_POST["salada"]);
$pwd = md5(mysqli_real_escape_string($connection, $_POST["arroz"]));
$result = mysqli_query($connection, "select name, id from users where email = '".$email."' and password = '".$pwd."'");
if (mysqli_num_rows($result) !==1){
$error='<div class="error-login">PHP: Invalid email or password</div>';
header("Location:index.php?error=".$error);
}else {
$nome = mysqli_fetch_row($result);
$_SESSION["name"] = $nome[0];
$_SESSION["id"]=$nome[1];
header ("Location: main.php");
}
}
}
?>
<?php
if($_SESSION['admin'] !=0){
header ("Location:admin.php");
}?>
Can someone tell me why isnt working? Is Syntax? If I compara the field "name", the restriction works...Thanks in advance!
The problem is, you haven't selected admin column in the SELECT query, you have only selected id and name columns. Plus, there's nowhere you're checking whether the logged in user is admin or not.
So the solution is, select the admin column in your SELECT query and make use of that column value to check whether the logged in user is admin or not, like this:
// your code
$result = mysqli_query($connection, "select name, id, admin from users where email = '".$email."' and password = '".$pwd."'");
if (mysqli_num_rows($result) !== 1){
$error='<div class="error-login">PHP: Invalid email or password</div>';
header("Location:index.php?error=".$error);
}else{
$nome = mysqli_fetch_row($result);
$_SESSION["name"] = $nome[0];
$_SESSION["id"] = $nome[1];
if($nome[2]){
// logged in user is admin
$_SESSION["admin"] = true;
}else{
// logged in user is not admin
$_SESSION["admin"] = false;
}
header ("Location: main.php");
exit();
}
// your code
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
I have already put user name and password in database, now what I am trying to do is when admin puts that user name and password that I have stored in database, they can access next page otherwise error.
if(isset($_REQUEST['submit'])) {
$user=$_REQUEST['user'];
$password=$_REQUEST['password'];
$q = mysql_fetch_assoc( mysql_query("SELECT * FROM adminlogin"));
$r = mysql_query($q);
if ( $user == "admin" && $password == "adminadmin" ) {
echo "welcome";
Header("Location: index.php");
}
}
Try with this:
if(isset($_REQUEST['submit'])) {
$user=$_REQUEST['user'];
$password=$_REQUEST['password'];
//Execute query, adjust the name of the columns to the one you've used in your table
$q = mysql_query("SELECT * FROM adminlogin WHERE user = '$user' and password = '$password'");
//Get the results from the query
$r = mysql_fetch_array($q);
//If any rows, the login is okay
if (mysql_num_rows($q) > 0) {
//User okay, redirect him to the success page
header("location: index.php");
}
After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;