I have the PHP code as below:
<?php
if(isset($_POST["tbn_submit"])){
$userName = $_POST["text_username"];
$pass = $_POST["text_password"];
//$sql = "SELECT * FROM tbluser WHERE username='".$userName."' AND password='".$pass."'";
$sql = "SELECT * FROM tbluser";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0){
while($row= mysql_fetch_array($res)){
$username=$row['username'];
$userpas = $row['password'];
$user_id=$row['userId'];
$user_role=$row['possition'];
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if($userName == $username && $pass == $userpas){
if($user_role=="Admin"){
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}else{
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else if($userName == $username && $pass != $userpas){
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
else if($userName != $username && $pass != $userpas){
//In this point I got insert multi time so I want it insert only 1 time to database
$query = "INSERT INTO tbluser(userId,username,password,possition,user_status) VALUES('','".$userName."','".$pass."','',1)";
$result = mysql_query($query) or die(mysql_error());
$id = mysql_insert_id();
if($result){
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
}
}else {
echo "re";
}
}
?>
This is my login page submission. When the user inputs their username and password, if the username and password are already in the database it will go to test some case like in code, but if the username is in the database but the password does not match it should display wrong password..
If the username and password don't exist in the database, the program should create username and password and go to other page. I have an error with this last case - I have inserted a lot of records in the database with the same data. I know it's because I wrote these entries in a while loop in my code but I don't know any other way of doing this. How can I populate my database with individual records and not write duplicate entries in my while loop?
All your logic is wrong:
there's no need to retrieve ALL the users to check if the user exists,
tbluser should restrict username to be UNIQUE to avoid duplicated entries,
passwords should be hashed,
the INSERT query uses unescaped variables,
inserting non matching user names will lead to have typos stored at the db,
mysql_* family of functions are deprecated
Using PDO
Login user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
$username = $res['username'];
$password = $res['password'];
$user_id = $res['userId'];
$user_role = $res['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
Register user
<?php
$dbh = new PDO('mysql:host=localhost;dbname=some_database_name', $user, $pass);
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$check = $_POST["passcheck"];
$statement = $dbh->prepare("SELECT * FROM tbluser WHERE username=:user");
$statement->bindParam(':user',$user);
$statement->execute();
/**
* Returns FALSE in case nothing is found
*/
$res = $statement->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$statement = $dbh->prepare("INSERT INTO tbluser (userId, username, password, position, user_status) VALUES ('', :user, :pass, '' , 1)");
$statement->bindParam(':user',$user);
$statement->bindParam(':pass',$pass);
$statement->execute();
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Using mysql_query (deprecated)
To validate any user:
<?php
if (isset($_POST["login"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* This line had the right idea!
*/
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
$username = $row['username'];
$password = $row['password'];
$user_id = $row['userId'];
$user_role = $row['possition'];
if ($pass == $password) {
$_SESSION['username'] = $username;
$_SESSION['uid'] = $user_id;
if ($user_role == "Admin") {
echo'<script>window.location="admin_project.php?uid='.$user_id.'";</script>';
}
else {
echo'<script>window.location="user_project.php?uid='.$user_id.'";</script>';
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong password.</span>";
}
}
else {
echo "<span style='text-align:center;color:red;'>Wrong username.</span>";
}
}
To register some user:
<?php
if (isset($_POST["register"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
/**
* Ask the user to type its password twice
*/
$check = $_POST["passcheck"];
$sql = "SELECT * FROM tbluser WHERE username='".mysql_real_escape_string($user)."'";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
if (mysql_num_rows($res) > 0) {
echo "<span style='text-align:center;color:red;'>Username exists.</span>";
}
else if ($pass != $check) {
echo "<span style='text-align:center;color:red;'>Password check doesn't match.</span>";
}
else {
$query = "INSERT INTO tbluser (userId, username, password, possition, user_status) VALUES ('','".mysql_real_escape_string($user)."','".mysql_real_escape_string($pass)."','',1)";
$res = mysql_query($sql) or die('The application found a problem and cannot process your request'); // die(mysql_error());
echo "<span style='text-align:center;color:red;'>Username registered.</span>";
}
}
Related
I did a lot of googling and tried many methods but checking for username existence in Mysqli database is not working. Everything is correct but still the user is getting registered even if there is a username in Database. Please help...My php version is 7 and phpmyadmin is 5.6. My code :-
<?php
session_start();
if (isset($_SESSION['id'])) {
header('Location: user.php');
die();
}
else {
if($_POST['submit']){
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$passhash = hash('sha512', $password);
$passhash2 = hash('sha512', $passhash);
$strlen = strlen("$password");
if ($strlen < 10) { {
$lesspass = "Use password of atleast 10 letters";
}
}
else {
$date = date("Y-m-d");
require ('setup.php');
$conn = new mysqli($localhost, $hostuser, $hostpass, $hostdb) or die("conn died");
$query1 = "SELECT * FROM member WHERE username = '$username'";
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($query1) > 0) {
die ("Username in use");
}
else {
$query2 = "SELECT from member WHERE email = $email";
$result2 = mysqli_query($conn, $query2);
if (($result2) > 0) {
$ee = "Email already exists";
}
else {
$query = "INSERT INTO member(username, password, registered, email, activated, status) VALUES('$username', '$passhash2', '$date', '$email', '1', '0')";
$result = mysqli_query($conn, $query);
if($result) {
header('Location: login.php');
}
else {
echo "There was a problem while connecting";
}
}
}
}
}
}
?>
I think the error is that you use mysqli_num_rows on the query string. Do it on the result:
if (mysqli_num_rows($result1) > 0) {
Also, you should take care about SQL injections (escape or use prepared statements), but that's another story. Not sure if strip_tags is sufficient.
I have defined a function to check user credentials and would like it to return true if the auth passed and false if it failed. my function is defined as follows:
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
}
} else {
$logged_in = False;
//$message = "Invalid USERNAME or PASSWORD";
//echo $message;
}
return $logged_in;
}
the problem I am running into is this, when I call the function and try to use what should be the returned value I get an error that the variable is not defined.
_userLogin($username, $password);
if ($logged_in == True){
'do something';
} else {
'do something else'
}
what am I doing wrong?
You are trying to use the variable $logged_in that is defined in function _userLogin outside the block. Assign the return value that is returned by the function like,
$logged_in = _userLogin($username, $password)
if ($logged_in == True){
'do something';
} else {
'do something else'
}
Also you will always receive TRUE because you are accessing variables $salt, $password outside the if block where they are being retrieved thus the fields not being assigned properly.
function _userLogin($username, $password){
include 'mysqli.php';
$logged_in = false;
$mysqli->select_db('Directories');
// query the login table for the username
$query = $mysqli->query("SELECT * FROM LOGININFO WHERE USERNAME='$username'");
$num_rows = mysqli_num_rows($query);
// check to see if the user exists
if ($num_rows > 0) {
$query = "SELECT * FROM LOGININFO WHERE USERNAME='$username'";
if ($result = $mysqli->query($query)){
$dbpass = '';
$salt = '';
while ($result_ar = mysqli_fetch_assoc($result)){
$dbuser = $result_ar['USERNAME'];
$dbpass = $result_ar['PASSHASH'];
$salt = $result_ar['SALT'];
}
// create the hash for password validation
$hash = hash('sha256', $salt.$password);
// validate the password
if ($hash == $dbpass){
$logged_in = True;
// retrieve info from the userinfo table
$query = ("SELECT * FROM USERINFO WHERE USERNAME='$username'");
if($result = $mysqli->query($query)){
while ($result_ar = mysqli_fetch_assoc($result)){
$name = $result_ar['name'];
}
}
}
} else {
echo "Could not connect to table: <br />".mysqli_error()."<br />";
}
}
return $logged_in;
}
PLEASE NOTE: I did not perform any logic checks other than fix your syntax
Replace your branching (where you use the function) with the simpler:
if( _userLogin($username, $password) ){
//success
}else{
//failure
}
I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.
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
How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}