Log in using different users - php

Here is my code for log in:
<?php
session_start();
include("conn.php");
$qry=mysql_query("Select * from tblru");
$qry2=mysql_query("Select * from tbladmin");
$credentials=mysql_fetch_array($qry);
if(isset($_POST['login'])){
if($_POST['user']==$credentials["user"]){
if($_POST['pass']==$credentials["pass"]){
$_SESSION['user']=1;
header("location:login.php");
exit();
}
else{
echo "<div style='position:absolute; right:230px; top:220px;'><b>WRONG PASSWORD<br>Re Input PASSWORD</b></div>";
}
}
else{
echo "<div style='position:absolute; right:230px; top:220px;'><b>WRONG USERNAME<br>Re Input Username</b></div>";
}
}
?>
I need help here with this log in code. I have created several users, but my log in only reads the first user registered. Could you help me with my code to be able to log in with the other accounts?

The easiest way to fix your issue is to change your query to something like this:
$login = false;
if(!isset($_POST['user']) || !isset($_POST['pass'])) {
// Something was missing
}
else {
$query = "SELECT * FROM tblru WHERE user='" . mysql_real_escape_string($_POST['user']) . "'"
. " AND pass='" . mysql_real_escape_string($_POST['pass']) . "' LIMIT 1";
$result = mysql_query($query);
$credentials = mysql_fetch_array($result);
if($credentials !== false) {
$login = true;
}
}
From here, $credentials will either be your verified user or FALSE.
Now that that's been said, however, please note that the mysql_* family of functions are deprecated and will be removed in future versions of PHP. Please visit this link to look at alternatives.
In addition, I noticed that you aren't hashing your password. This is a bad idea; storing your password in plaintext in the server makes it an inviting target. You can read more about it here.

Related

include user ID in session

Currently my php login form will only carry acrocss the username on the session, I want this to carry across the user id (automatically created when the user registers).
As shown below I have included the user_id but it is not displaying on my webpage, the username is however.
Just wondering if anyone can help me with this? (I'm new to PHP)
Login process:
require_once('connection.php');
session_start();
if(isset($_POST['login']))
{
if(empty($_POST['username']) || empty($_POST['PWORD']))
{
header("location:login.php?Empty= Please Fill in the Blanks");
}
else
{
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if(mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];
header("location:../manage_event.php");
}
else
{
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
}
else
{
echo 'Not Working Now Guys';
}
Session on next page:
session_start();
if(isset($_SESSION['User']) || isset($_SESSION['user_id']))
{
echo ' Welcome ' . $_SESSION['User'].'<br/>';
echo ' User ID ' . $_SESSION['user_id'].'<br/>';
}
else
{
header("location:login/login.php");
}
Though your security is questionable, i’ll answer your question anyway. As stated in another response you aren’t assigning your variables the right way. See an example here
The following code will fix your problems contrary to the other solution:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
if ($result = mysqli_query($con, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id']=$row['user_id'];
header("location:../manage_event.php");
}
}else {
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
Make sure to replace this code with your old fetching code block. Thus in the first ‘else’ clause.
How about assigning the fetched result to $row:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if( $row = mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];

Unique identifier link value receiving failure in PHP isset GET

I'm trying to verify registration via email with sending of unique identifier link to user.
I use it from remote server. Server, username, password, database values are correct, works fine with other .php-s, only difference verify.php has connection included, instead require 'connection.php';, but I'm not sure if connection produces following failure.
Sends:
$message = "<p>Hello, dear $user</p><a href='https://mypage.info/php/reg/verify.php?vkey=$vkey'>Confirm Account</a>";
and receives on email:
https://mypage.info/php/reg/verify.php?vkey=4bf65cf02210b304143589e6dc3714c0
link to verify.php, but php throws Something went wrong, or
if instead die I'll check echo 'VKey: '. $vkey; or echo $mysqli->error; shows nothing.
Seems like by some reason if (isset($_GET['vkey'])) does not receives vkey correctly. I'm not sure what I'm doing wrong here:
Alert! This example code shows insecure method since accepts SQL parameters directly from user input. Requires Prepared Statements and Bound Parameters, real_escape_string()
<?php
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
$mysqli = NEW MySQLi ('server','username','password','db');
$resultSet = $mysqli->query("SELECT verified, vkey FROM registration WHERE verified = 0 AND vkey = '$vkey' LIMIT 1");
if ($resultSet->num_rows == 1)
{
$update = $mysqli->query("UPDATE registration SET verified = 1 WHERE vkey = '$vkey' LIMIT 1");
if($update){
echo "Your account has been verified. You may now login.";
} else {
echo $mysqli->error;
}
}
else
{
echo "This account invalid or already verified";
}
} else {
die("Something went wrong");
}
?>
Your code looks in the $_POST array instead of $_GET
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
SUGGESTION: instrument everything possible, and post back what you find.
For example:
<?php
echo "vkey=" . $_GET['vkey'] . "...<br/>";
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
echo "vkey=" . $vkey . "...<br/>";
$mysqli = NEW MySQLi ('server','username','password','db');
echo "mysqli: SUCCEEDED...<br/>";
$resultSet = $mysqli->query("SELECT verified, vkey FROM registration WHERE verified = 0 AND vkey = '$vkey' LIMIT 1");
echo "resultSet: SUCCEEDED...<br/>";
echo "resultSet->num_rows=" . $resultSet->num_rows . "...<br/>";
if ($resultSet->num_rows == 1)
{
$update = $mysqli->query("UPDATE registration SET verified = 1 WHERE vkey = '$vkey' LIMIT 1");
echo "update: SUCCEEDED...<br/>");
if($update){
echo "Your account has been verified. You may now login.";
} else {
echo $mysqli->error;
}
}
else
{
echo "This account invalid or already verified";
}
} else {
echo "ERROR STATE: " . $mysqli->error . "...<br/>";
die("Something went wrong");
}
?>
And no, I can't think of "... why md5 string" could be the culprit. But I think the above instrument (or similar) might help us determine EXACTLY where the problem is occurring ... and thus how to resolve it.
'Hope that helps...

Error Updating Old Password with with password_hash

I've a problem when updating the old password with the new one password_hash, it always said Old password is wrong.
The table: pegawai
Field: nokom, nama, uol1
Here's my code:
<?php session_start();
require "config.php";
$nokom = $_POST['nokom'];
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
$pswbaru = password_hash($_POST['pswbaru'], PASSWORD_DEFAULT);
$cari = "SELECT * FROM pegawai WHERE nokom ='".$nokom."'";
$result = mysqli_query($conn,$cari);
if (mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
if(password_verify($pswlama, $data['uol1']))
{
$perintah = "UPDATE pegawai SET uol1 = '$pswbaru' WHERE nokom = '$nokom' ";
if (mysqli_query($conn, $perintah))
{
echo "<script>alert('Success');location.replace('home.php')</script>";
}
else
{
echo "Error updating record: " . mysqli_error($conn);
}
}
else
{
echo "<li>Old password is wrong!</li>";
}
}
}
else
{
echo "Data not found";
}
?>
Any help will be great, thanks.
You are putting a hash in both arguments of password_verify. Read the manual of password_verify and you'll see that the first argument is not supposed to be a hash, but the password itself to compare against the hashed password (argument 2) that is stored in your database.
You are hashing the password before you pass it to password_verify here:
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
...
if(password_verify($pswlama, $data['uol1']))
You should be passing $_POST['pswlama'] directly to password_verify.
change this
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
to this. password_verify will handle the rest.
$pswlama = $_POST['pswlama'];
keep the rest of your code the same.

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

HTML Login using PHP and mySQL issues

I am creating a web based application using HTML5, it is connected to a mySQL database. I am trying to use PHP to connect the two.
I am trying to create a login page that checks the number and password against that in the database to see if it is a valid login.
Hard coding the number and password works fine but when trying to apply it to the database I always get a 'Logged in' message even though the login credentials are invalid. I tried using both $_POST and $dbRow but to no avail.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$s_number) {
if ($_POST["passwd"]==$s_pass) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
I am very new to PHP. I have searched for other examples but there seems to be many different ways to do this that I dont understand. Any help would be much appreciated!
Try this:
<?php
include ("dbConnect.php");
if(isset($_POST["snumber"]))
{
$s_number = mysql_real_escape_string($_POST["snumber"]);
$s_pass = mysql_real_escape_string($_POST["passwd"]);
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_assoc($dbResult);
if ($dbRow["staff_number"]==$s_number && $dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
}
else {
echo "<p>Bad username and password</p>";
}
?>
PS: Go for mysqli or PDO ;) ; you can try a count or a mysql_num_rows to see if the match result is zero.
Saludos .
Adrian and Robert have addressed parts of the problem.
If you're just learning PHP then all the more reason that you should start writing your code to use the mysqli API rather than the deprecated mysql_ functions. They are almost the same - but the latter will disappear at some point in the future.
If you're writing a login page then you're presumably concerned about security - however without properly escaping your code it's trivial to bypass the control mechanism (and in some cases exposes your database to serious vandalism / disclosure issues).
Further even by fixing the SQL injection problem, it's easy to get past the authentication using session fixation.
The next mistake is that you never check if the interactions with the database are successful or not.
Hence this looks like a duplicate of this question - although I've not flagged it as such due the poor quality of the answers / discussion on that post.
Further, since you've only SELECTed rows from the database matching the username / password, why do you then compare the username and password with the data you retrieved?
It's generally considered good security practice, to NOT explain why the login failed when some provided authentication details.
So trying again....
<?php
session_start();
include ("dbConnect.php");
function auth($user, $pass)
{
$user=mysqli_real_escape_string($user);
$pass=mysqli_real_escape_string($pass);
$qry="SELECT SUM(1) AS matches
FROM YOURDB.staff_details
WHERE staff_number='$user'
AND password='$pass'";
$res=mysqli_query($qry) || die "Sorry - not available";
$r=mysql_fetch_assoc($res);
return $r['matches'];
}
if (auth($_POST["snumber"], $_POST["passwd"])) {
session_regenerate_id();
echo "<p>Logged in!</p>";
} else {
echo "<p>Sorry - invalid authentication</p>";
}
You need to use $dbRow instead of $_POST.
As currently you are just comparing $_POST with $_POST.
It's always going to be the same.
Secondly, you've specified different field names in your query and array key.
Try this.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$dbRow['staff_number']) {
if ($_POST["passwd"]==$dbRow['password']) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
EDIT: Although you don't really need to do the If Statement after.
If you're getting a result from your DB query with the Username/Password matching, the credentials are correct.
So you could do,
if (!empty($dbRow)){
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}

Categories