This is my login.php code. User is logged in even "status" is set to "yes". How can I verify if the user is banned and can I add more statuses like "suspend", "deactivated"?
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("DBname", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$sql = mysql_query("INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')", $connection);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Firstly don't use mySQL anymore, it is deprecated and insecure. You should look into using mySQLi or PDO instead.
The problem you are having is because $row has no value.
You are missing:
$row = mysql_fetch_assoc($result)
So it would read like this:
$query = mysql_query("select * from users where password='$password' AND username='$username' AND", $connection);
$rows = mysql_num_rows($query);
$row = mysql_fetch_assoc($result);
if($row[‘status’]==’yes’){
header("banned.php");
}
Here it is rewritten as mySQLi, use this version instead and research the difference:
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db($connection, "DBname");
// SQL query to fetch information of registerd users and finds user match.
$query = "select * from users where password='$password' AND username='$username'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$rows = mysql_num_rows($query);
if($row[‘status’]==’yes’){
header("banned.php");
} else if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
$query = "INSERT INTO logs (`uniqueId`, `fileAccessed`, `action`, `userIp`, `userPort`, `serverIp`, `fullPath`, `protocol`, `serverVersion`, `timestamp`) VALUES ('$username', '$filename', 'Logged In', '$usrip', '$usrport', '$servip', '$scriptpath', '$servprotocol', '$servver', '$timestamp')";
$result = mysqli_query($connection, $query);
header("location: ../pages/profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
Related
im trying to verify the users hashed password with their input but i cant get it working, so far it idenfities if theres a user with that username but it just wont verify the password. here is my code
<?php
$serverName = "localhost"; //Variables to access the user database
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database); //Connect to the database
if(!$conn){ //If the database failed to connect
die("Database failed to connect: " .mysqli_connect_error()); //Display an error message
}
$username = $_POST['username']; //set the username/ password varaibles
$password = $_POST['password'];
$hashPass = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password
$sql = "SELECT * FROM users WHERE username = ?"; //Select all usernames and passwords
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$count = mysqli_num_rows($result); //Count how many results there are
if ($count == 1)
{
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
if(password_verify($password, $result )){
$count = 2;
}
}
if($count == 2) //If there is 1 account that matches
{
$stmt->close(); //Close the statment and connection
$conn->close();
session_start();
$_SESSION["LoggedUser"] = $username; //Log the user in
$_SESSION["lastPage"] = "login.php";
header("location: profile.php"); //Direct the user to their profile
}else //if there is no accounts that match
{
array_push($errors, "Username or password is incorrect");
session_start();
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php"; //Make this page the last page
header("location: index.php"); //Go to the homepage
}
?>
any help is appriciated, thanks
You are doing a lot of things you dont need to do.
A SELECT * will return all the columns so you dont need to do another SELECT for just the password.
Also you should not password_hash() the password again, when checking a password against the one already stored on the database. Use password_verify() and that will do all the checking. So you pass it the hashed_password from the database and the plain text password the user just entered on the screen, it will return true or false telling you if the password entered matched the hashed one on the database
<?php
// always do this early in the code
session_start();
$serverName = "localhost";
$username = "root";
$password = "";
$database = "snake_database";
$errors = []; //Array of all the errors to display to the user
$conn = mysqli_connect($serverName, $username, $password, $database);
if(!$conn){
die("Database failed to connect: " .mysqli_connect_error());
}
// dont hash password again
//$hashPass = password_hash($password, PASSWORD_DEFAULT);
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST['username']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(password_verify($_POST['password'], $row['password'] )){
// ----------------^^^^^^^^^^^^^^^^^^--^^^^^^^^^^^^^^^^
// Plain text pwd hashed pwd from db
$_SESSION["LoggedUser"] = $_POST['username'];
$_SESSION["lastPage"] = "login.php";
header("location: profile.php");
// put exit after a redirect as header() does not stop execution
exit;
}
} else {
$errors[] = "Username or password is incorrect";
$_SESSION["loginErrors"] = $errors;
$_SESSION["lastPage"] = "login.php";
header("location: index.php");
exit;
}
?>
I have created a database with a table (UserPass) which essentially stores Usernames and Passwords.
Now in my form I want to ask a user to input his username and password and while testing this, I realized that I can input any username from the database and any password to login.
Is it possible to select in the SQL query the password that is in the same line as the username?
I tried something like:
$username = $_POST['username'];
$sql = "SELECT Password FROM UserPass WHERE Username = $username";
But the following mysqli_query failed:
$query = mysqli_query($cxn, $sql);
So here is the entire action.php script:
<?php
include "info.php";
include "god.php";
session_start();
if($_POST['god'] == $god)
{
header( "refresh:0;url=../web.html" );
}
else if(empty($_POST['god']))
{
}
else
{
echo "Can't you read: DON'T TRY!!!!!!!";
exit();
}
$cxn = mysqli_connect($host, $user, $password, $dbname) or die("Go");
//check username
$userI = $_POST["username"];
$userSql = "SELECT Username FROM UserPass ";
$result = mysqli_query($cxn, $userSql) or die("Query failed!");
while($line = mysqli_fetch_assoc($result))
{
extract($line);
foreach ($line as $key => $val)
{
if($_POST['username'] == $val)
{
//check for password
$username = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT Password FROM UserPass";
$passres = mysqli_query($cxn, $sql) or die("Request cannot be handled now.");
while ($passline = mysqli_fetch_assoc($passres))
{
extract($passline);
foreach ($passline as $k => $v)
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
}
else
{
session_destroy();
}
}
}
}
}
}
/*
if($userI == $line['Username'])
{
//check for password
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$res = mysqli_query($cxn, $sql) or die("Pass query failed");
$passline = mysqli_fetch_assoc($res);
if($pass == $passline['Password'])
{
header( "refresh:4;url=../web.html");
session_start();
echo "Login succesful, session started, session id: ";
}
}
*/
/*
if($_POST['username'] == $val)
{
//check for password
$b = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM UserPass";
$passres = mysqli_query($cxn, $sql);
$passline = mysqli_fetch_row($passres);
foreach ($passline as $k => $v )
{
if($_POST['password'] == $v)
{
header( "refresh:0;url=../web.html");
session_start();
}
}
}
*/
/*
else
{
print("Destroying Laptop...US Government...Destroying Laptop...\n");
exit();
}
*/
?>
You just need to check if there is a record that contains both username and password of the same user:
$password = mysqli_real_escape_string($password);
$username = mysqli_real_escape_string($username);
$sql = "SELECT Password FROM UserPass WHERE Username = '$username' AND Password = '$password'";
if there is 1 such result, it is OK.
BTW, you should not store passwords in plain text - instead use one-way hashing function and compare only the hashes of the passwords.
Your SQL query should contain an 'AND' like this:
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$sql = "SELECT * FROM UserPass WHERE username = '{username }' AND password = '{$password}' LIMIT 1";
$query = mysqli_query($link, $sql);
if ($query && mysqli_num_rows($query)>0) {
//user is authenticated
}
?>
By using the logical operator AND your query must match two conditions to give you an answer. That conditions should be known only by the users.
Also please do not store the password field as clear text in database. It's not safe. You should use sha1 hash. For more information about this please take a look here http://en.wikipedia.org/wiki/SHA-1
My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.
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.';
}
}
Okay, so I want to make a simple login page. I've created a register page successfully, but i can't get the login thing down.
login.php:
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if(!$con){
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if(mysql_num_rows($result) == 1 {
$_SESSION = true;
header('Location: indexlogin.php');
}
else {
echo = "Wrong username or password." ;
}
?>
indexlogin.php just echoes "Login successful." What am I doing wrong?
Oh, and just FYI- my database is "users" and my table is "data".
<?php
session_start();
include("mainmenu.php");
$usrname = mysql_real_escape_string($_POST['usrname']);
$password = md5($_POST['password']);
$con = mysql_connect("localhost", "root", "g00dfor#boy");
if (!$con) {
die(mysql_error());
}
mysql_select_db("users", $con) or die(mysql_error());
$login = "SELECT * FROM `users` WHERE (usrname = '$usrname' AND password = '$password')";
$result = mysql_query($login);
if (mysql_num_rows($result) == 1) {
$_SESSION['logged_in'] = true;
header('Location: indexlogin.php');
exit;
} else {
echo "Wrong username or password.";
}
?>
I added mysql_real_escape_string() to prevent SQL injection.
No, I didn't because you already had it.
I cleaned up the formatting of the code a bit.
I changed $_SESSION = true; (which doesn't make sense) into $_SESSION['logged_in'] = true;. Then, in indexlogin.php you can do something like if ($_SESSION['logged_in']) { echo $secret; }
I fixed echo = "Wrong username or password."; to echo "Wrong username or password.";
I added a closing bracket near mysql_num_rows($result) == 1.
You said:
my database is "users" and my table is
"data".
If this is correct, you will need to change SELECT * FROM users to SELECT * FROM data.
I don't think you can set $_SESSION = true, because $_SESSION is an array. Try $_SESSION['logged_in'] = true.