PHP Username and Password verification - php

I'm currently working on a class project where I have to verify the username and password against a database. I stored the values of the username and password in individual arrays and I'm trying to verify that the user input matches one of the values in there. However, that's not happening, and I'm not sure how to fix it. Thanks for your help!
<?
connectDB();
$sql = "SELECT* FROM employee";
$result = mysqli_query($db,$sql) or die ("SQL error: " . mysqli_error());
$row = mysqli_fetch_array($result);
$password = array();
$username = array();
while($row = mysqli_fetch_array($result))
{
$password[] = $row['emp_pword'];
$username[] = $row['emp_username'];
}
var_dump($password);
var_dump($username);
?>
<?php if (isset($_REQUEST['page1_submit'])) {
if (($_REQUEST['pword'] == $password) and ($_REQUEST['user'] == $username)) {
header('location:home_agent.php');
} else { ?>
<h2>Wrong Password! Try again.</h2>
<form method="POST" action="login.php">
<table class="info">
<tr>
<th>Username:</th>
<td><input type="text" NAME="username" />
</td>
<th>Password:</th>
<td><input type="password" NAME="pword" /></td>
</tr>
</table>
<input class="submit" type="submit" name="page2_submit" value="SUBMIT" />
<input class="submit" type="reset" value="RESET" />
</form>
<?php }

ME TOO THINKS YOU ARE WRONG .
YOU JUST EXECUTE QUERY
" SELECT * FROM TBLE_NAME WHERE username=$username AND password=$password"
check this query gives a non empty list for verify login
thats all.

Related

How to create a php page with login using cookies?

I want to create an admin page with login and if the user is logged and he is admin in my database the content must appear, if is not an admin the content will appear but without some privileges. And if the user and password did not match with any user and password form database a message error must appear.
This is my HTML code:
<form action="admin.php" method="post">
<table>
<tr><td>
<label>User:&nbsp&nbsp&nbsp</label> </td> <td><input type="text" class="text" name="user"/> <span></span>
</td></tr>
<tr><td>
<label>Password:</label> </td> <td> <input type="password" class="text" name="pass"/> <span></span>
</td></tr>
<tr ><td colspan="2">
<p align=center><input type="submit" class="submit" value="Log In" /> </p>
</td></tr>
This is my PHP code:
<?php
require_once('config.php');
$user = $_POST['user'] ;
$pass = $_POST['pass'] ;
$sql='SELECT * FROM users';
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
?>
My table is:
|ID_user| user |password|is_admin|
| 1 |admin | admin | 1 |
Thank you!
Your SQL is already.. not good. You're using mysql_, but let's skip that for now. You're not checking if the user exists and if the passwords match.
$result = mysql_query("SELECT * FROM `users` WHERE `username` = $user AND `password` = $pass");
if(mysql_num_rows($result) > 0) { //so if user exists where user = adimouse91 and pass = mouse, it'll be one
echo 'this is content for logged in users';
}
$isAdmin = mysql_fetch_assoc($result);
if($isAdmin['is_admin'] == '1') {
echo 'this is content for admins';
}
I have not taken into account password salts and hashing in general (which you should do!) or sessions. Sessions make your life easier (imagine if you could just do if($_SESSION['admin'] == 1) { }!).
I did it! The answer:
admin.php
<div id="content">
<div id="main_r">';
require_once('config.php');
if (isset($_GET['err'])){
$err=$_GET['err'];
if($err==1)
echo'<h4>Pls insert user and pass!</h4>';
else if ($err==2)
echo'<h4>User and pass are incorect!</h4>';
}
if(!isset($_COOKIE["TestCookie"]))
echo'
<form action="dologin.php" method="post">
<table>
<tr><td>
<label>User:&nbsp&nbsp&nbsp</label> </td> <td><input type="text" class="text" name="user"/> <span></span>
</td></tr>
tr><td>
<label>Pass:</label> </td> <td> <input type="password" class="text" name="pass"/> <span></span>
</td></tr>
<tr ><td colspan="2">
<p align=center><input type="submit" class="submit" value="Log In" /> </p>
</td></tr>
</table>';
else{
$curr = $_COOKIE['TestCookie'];
$sql = "SELECT user, admin FROM useri WHERE ID_user='$curr'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo'<h4>Welcome '.$row['user'].'</h4>
</div>';
}
dologin.php
<?php
require_once('config.php');
if (isset($_POST['user']) && isset($_POST['pass']))
{
$user = $_POST['user'] ;
$pass = $_POST['pass'] ;
$pass_hash = md5($pass);
$err = 0;
if (!empty($user) && !empty($pass))
{
$sql="SELECT ID_user FROM useri WHERE user='$user' AND password='$pass_hash'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($result)
{
$num_rows = mysql_num_rows($result);
if($num_rows==0)
$err=2;
else if ($num_rows==1)
{
$ID_user = $row['ID_user'];
//echo $ID_user;
setcookie("TestCookie",$ID_user, time()+3600);
}
}
} else
$err=1;
header("Location: http://yoursite/admin.php?err=".$err);
exit;
}
?>

PHP: Page not redirected back to the login page

I have a login.html file with a form having username and password field and on submit button it checks the values from the form with the mysql database.
My PHP code is in different file called login.php
The problem is that it works fine when i put correct username and password. But if i put wrong inputs or keep them empty then instead if redirecting to the login.html page it redirects to login.php page.
login.php
<?php
### Check if the Submit button is clicked
if (isset($_POST['btnSubmit']))
{
# code...
//$uname=$_POST['uname'];
//$pswd=$_POST['pswd'];
#### Connection to mySQL ####
$conn=mysqli_connect("localhost","root","","vishal") or die("Unable to connect to MySQL");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,"SELECT * FROM login where username = '$_POST[uname]' AND password = '$_POST[pswd]'") or die(mysql_error());
$row = mysqli_fetch_array($result) or die(mysql_error());
$username=$row['username'];
$password=$row['password'];
if (!empty($username) AND !empty($password))
{ # code...
//$_SESSION['username'] =$password;
header('location:welcome.html');
}
else //(empty($username) AND empty($password))
{ # code...
header('location:login.html');
die();
}
}
?>
login.html
<form action="login.php" name="login_form" method="post" enctype="multipart/form-data" target="_self">
<fieldset style="width:300px; margin:auto; margin-top:100px; border:solid 2px #900; background-color:#CCC; border-radius: 50px">
<h1 style="color:#306;"> <center> Login Form </center></h1> <br> <br>
<div style="margin-left:30px;">
<table>
<tr>
<td align="right"> <label for="uname"> <strong>Username :</strong> </label> </td>
<td> <input type="text" title="Username" id="uname" name="uname" placeholder="Username" /> </td>
</tr>
<tr><td> </td><td> </td> </tr>
<tr>
<td align="right"> <label for="pswd"> <strong>Password :</strong> </label> </td>
<td> <input type="password" title="Password" id="pswd" name="pswd" placeholder="Password" /> </td>
</tr>
<tr><td><br /> </td><td> <br /></td> </tr>
<tr>
<td></td>
<td> <input type="submit" title="Submit" name="btnSubmit" id="btnSubmit" value="Submit" style="width:100px; height:26px; font-weight:bold;" /> </td>
</tr>
<tr><td><br /> </td><td> <br /></td> </tr>
</table>
</div>
</fieldset>
</form>
use this code :
$result = mysqli_query($conn,"SELECT * FROM login where username = '$_POST[uname]' AND password = '$_POST[pswd]'") or die(mysql_error());
$row_count = mysql_num_rows($result);
if($row_count==1) {
$row = mysqli_fetch_array($result) or die(mysql_error());
$username=$row['username'];
$password=$row['password'];
header('location:welcome.html');
} else {
header('location:login.html');
die();
}
You have to do like this in login.php
<?php
### Check if the Submit button is clicked
if (isset($_POST['btnSubmit']))
{
$conn=mysqli_connect("localhost","root","","vishal") or die("Unable to connect to MySQL");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(!empty($_POST['uname']) && !empty($_POST['pswd'])) {
$result = mysqli_query($conn,"SELECT * FROM login where username = '$_POST[uname]' AND password = '$_POST[pswd]'") or die(mysql_error());
$row_count = mysqli_num_rows($result);
if($row_count==1) {
$row = mysqli_fetch_array($result) or die(mysql_error());
$username=$row['username'];
$password=$row['password'];
header('location:welcome.html');
} else {
header('location:login.html');
die();
}
} else {
header('location:login.html');
die();
}
}
?>

PHP MySQL Sign up with pre defined username and registration id

I'm trying to make a website with a member section. To signup on the member section, you must already be in the database. You're given your username and password, then when you signup you can enter your email, address, and password.
So my problem is that I'm getting an error saying that the username or reg_id were incorrect, when I know that I am entering the correct info.
else {
mysql_close($con);
header("location: index.php?signup&error-msg=Incorrect Username or Registration ID.");
}
Here is my Login Form:
<form action="function.php?signup" method="post">
<table cellspacing="20" class="span12">
<tr>
<td>
<input type="text" name="name" placeholder="Full Name">
</td>
</tr>
<tr>
<td>
<input type="email" name="email" placeholder="Email">
</td>
</tr>
<tr>
<td>
<input type="text" name="address" placeholder="Address">
</td>
</tr>
<tr>
<td>
<input type="text" name="reg_id" placeholder="Your Registration ID">
</td>
</tr>
<tr>
<td>
<input type="password" name="password" placeholder="Password">
</td>
</tr>
<tr>
<td>
<input type="submit" placeholder="Confirm Signup" value="Confirm Signup">
</td>
</tr>
</table>
</form>
On the function.php I have a bunch of different functions etc. but the one for the signup form is:
elseif (isset($_GET['signup'])) {
$username = $_POST['username'];
$reg_id = $_POST['reg_id'];
$qry = mysql_query("
SELECT *
FROM users
WHERE username = '$username'
AND registration_id = '$reg_id' ", $con);
if (!$qry) {
mysql_close($con);
die("Query Failed: " . mysql_error());
} else {
$row = mysql_fetch_array($qry);
}
if ($_POST['username'] == $row["username"] && $_POST['reg_id'] == $row["registration_id"]) {
$password = $_POST['password'];
$email = $_POST['email'];
$address = $_POST['address'];
$qry = mysql_query("
INSERT INTO users
(password, profile_email, profile_address)
VALUES ('$password', '$email', '$address')", $con);
if (!$qry) {
die("Query Failed: " . mysql_error());
} else {
header('location: index.php?success-msg=You have successfully signed up');
}
}
else {
mysql_close($con);
header("location: index.php?signup&error-msg=Incorrect Username or Registration ID.");
}
}
I'm not sure what I messed up on, or if I even did that right, as I am still learning. I would like to thank anyone who helps me in advance, all help is much appreciated.
-James
$_POST['username'] should be $_POST['name'] accoding to HTML form.
Use update instead of INSERT.
Following is the corrected PATCH:
$qry = mysql_query("UPDATE users SET password='$password',profile_email='$email',profile_address='$address'
WHERE registration_id='$reg_id'");
you could use something like this :
if (isset($_GET['signup'])){//if
$username = $_POST['name'];
$reg_id = $_POST['reg_id'];
$qry = mysql_query("SELECT * FROM users WHERE username='$username' AND registration_id='$reg_id'", $con) or die(mysql_error());
$row=mysql_num_rows($qry);
if($row == '1'){ ///if regcode exists
////insert into database
$password = $_POST['password'];
$email = $_POST['email'];
$address = $_POST['address'];
$qry2 = mysql_query("INSERT INTO
users(password,profile_email,profile_address)
VALUES ('$password','$email','$address')", $con) or die(mysql_error());
header('location: index.php?success-msg=You have successfully signed up');
}///if regcode exists
else{
///didn't find the reg id
header("location: index.php?signup&error-msg=Incorrect Username or Registration ID.");
}
}//if

How to fix this PHP Forgotten Password Script?

So basically, I'm trying to make a simple, yet secure, forgotten password script.
There are two scripts, one that allows the user to enter their email address. This will then send them an email with a link that they must visit to save their new password.
The second script is where the link leads to. This script saves the new password.
For security purposes, I made a new table within my database called 'token'. It has three fields; token, email, used. Token is a random generated string of 10 letters and numbers, email is just that users email address, and used is an integer of either 1 or 0 indicating whether or not the token has been used.
You will be able to understand far more of my structure once you read over the two scripts. They are not to long, and not complex at all.
What is going wrong
Okay, so there is only one small thing going wrong, and this is within the reset-password.php script. This is where the users come to after they receive the email. Basically, I type in a new password, and click 'Reset Password', yet nothing happens. No errors or confirmations are shown, along with nothing changing within my database. I can't seem to debug this, and have been searching and trying for hours now. All help and suggestions would be greatly appreciated.
Please try to keep in mind that I am still a newbie at PHP and MySQL. Been working with PHP for approximately 8 weeks now, and MySQL for only 2.
forgot-password.php
<?php
//Forgotten password script
//Variable to save errors
$errors = array();
$email = $_POST['email'];
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$query = "SELECT email FROM users WHERE email='" . $email . "'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num==0)
{
echo ("<div style='color:red;'>Email address is not registered</div>");
die();
}
$token = getRandomString(10);
$query = "INSERT INTO tokens (token,email) VALUES ('".$token."','".$email."')";
mysql_query($query);
//function to renerate the token
function getRandomString($length)
{
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++)
{
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
//Send the reset link to the user
function mailresetlink($to,$token)
{
$subject = "Password Reset";
$message = '
<html>
<head>
<title>Password Reset</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: Password Reset <noreply#domain.com>' . "\r\n";
if(mail($to,$subject,$message,$headers))
{
echo "We have sent the password reset link to your email at <strong>".$to."</strong>";
}
}
//If email is posted, send the email
if(isset($_POST['email']))
{
mailresetlink($email,$token);
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>Email Address: </td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Reset My Password" /></td></tr>
<input type="hidden" name="register" value="TRUE" />
</form>
</table>
reset-password.php
<?php
//Reset password script
$token = $_GET['token'];
$email;
include 'config.php';
mysql_connect("$db_host", "$db_username", "$db_password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(!isset($_POST['newpassword']))
{
$query = "SELECT email FROM tokens WHERE token='" . $token . "' AND used = 0";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$email = $row['email'];
}
if ($email != '')
{
$_SESSION['email'] = $email;
}
else
{
echo "Invalid link or Password already changed";
}
}
$pass = $_POST['newpassword'];
$email = $_SESSION['email'];
//Save new password
if(isset($_POST['newpassword']) && isset($_SESSION['email']))
{
$query = "UPDATE users SET password = SHA('$password') WHERE email='" . $email . "'";
$result = mysql_query($query);
if($result)
{
mysql_query("UPDATE tokens SET used=1 WHERE token='" . $token . "'");
}
echo "Your password has been changed successfully";
if(!$result)
{
echo "An error occurred. Please try the again or contact us at admin#domain.com";
}
}
?>
<table align="center" style="padding-bottom:40px;">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
Please, if you need any more information or code, please do not hesitate to ask.
Thanks in advance!
I don't see anywhere where you are passing the token parameter to the server on the reset page after entering the new password parameter. You should have another hidden <input /> control, I would expect. $_SERVER['PHP_SELF'] does not return query string parameters. That is likely the cause of your current problem.
Specifically,
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
</form>
</table>
should be
<table align="center" style="padding-bottom:40px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" id="password"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Change Password"></td></tr>
<input type="hidden" name="reset" value="TRUE" />
<input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
</form>
</table>
Make sure you also change any $_GET['token']s to $_REQUEST['token'] as it will be GET the first time, then POST the second.
That being said, your much larger problem is the ability for me to bypass all your security by specifying ' or 1=1 or ' as my token. Or, I could be mean and do a nice '; update users set password = SHA('IKnowThisPassword') where username = 'admin'; --
Moral of the story being parameterized SQL (How can I prevent SQL injection in PHP?)

Login page that gives error messages and submits to self

im currently stuck trying to create a log in form that submits to its self so that if theres any errors they'll be displayed above the login form rather than being sent to another page. Also if the login is successful then they're sent to the desired page. Here's my code below, I appreciate any help, Thanks!
<?php
if ((isset($_REQUEST['username'])) && (isset($_REQUEST['password']))) {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
}
$query = mysql_query("SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'");
$numrows = mysql_num_rows($query);
if ($numrows != 0) {
while ($row = mysql_fetch_assoc($query)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($adminusername == $dbusername && ($adminpassword == $dbpassword)) {
$_SESSION['username'] = $adminusername;
header("Location: admin.php");
}
} else {
echo " ($error) Username and password do not match";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
I've indented your code so you can see the structure more clearly.
If the username and password are blank then an error will be output, but the database will still be queried.
You're not checking whether the database query actually works. You should check $query is not false, and if it is report an error.
You're checking the username and passwords match twice (once in the SQL and once again later), this is overkill, and besides you're not reporting if the second check fails.
header() will only work if you've not sent any output yet... if there's anything output before the code you've shown, even a blank line outside of PHP, then the header won't work.
On its own, this works for me (sql injection potential aside):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
} else {
$sql = "SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['username'] = $adminusername;
header('Location: /admin.php');
exit;
}
echo "<b>Username and password do not match</b><br/>";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
To submit a <form>, you need a submit button; you've got:
<button type="submit">Log In</button>
try:
<input type="submit" value="Log In" />
I don't think you're currently submitting the form, so nothing will happen when you click submit.
instead of
header("Location: admin.php");
try java script
echo "<script>window.location = 'admin.php';</script>
if you have already outpu to the page header wont work
My solution echos the form with the error below it within a div. I'm still learning but I hope it helps someone.
<div>
<?php
//make sure the form action='' is set to itseslf
echo "
<form action='self_page_name' method='post'>
<table>
<tr>
<td>UserName:</td>
</tr>
<tr>
<td><input type='text' name='username' required='required' /></td>
</tr>
<tr>
<td>Password: </td>
</tr>
<tr>
<td><input type='password' name='password' required='required' /></td>
</tr>
<tr>
<td><input type='submit' name='submit' value='Login' /></td>
</tr>
</table>
</form>
";
//////////your php validation script here////////////
?>
</div>

Categories