when password and username match in DB, Error show up? - php

when write anything in form and click Enter button, there is no error, but when i write the username and password correct the error show up
i tried echo "$_POST['username']"; // print username if username doesn't match ?
Error:
Notice: Undefined index: username in ..
Notice: Undefined index: password in ..
this is my form
<form action="2.php" method="post">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Enter" />
</td>
</tr>
</table>
</form>
and this my second page
<?php
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die('Could not connect');
exit;
}
mysql_select_db('dbName') or die( "Unable to select database");
$query = "SELECT * FROM admin WHERE username = '$username'";
$result = mysql_query($query) or die(mysql_error());
$num = mysql_num_rows($result); // number of rows
if ($num > 0){
$i = 0;
while ($i < $num){
$row = mysql_fetch_array($result);
if ( ($password) == $row['password'] && ($username) == $row['username'] ){
header('location:2.php');
$_SESSION['sessionname'] = $username;
$_SESSION['sessionpass'] = $password;
}
elseif ( ($password) != $row['password'] && ($username) == $row['username'] ) {
echo "Wrong Password <a href='1.php' >Click Here</a>";
}
$i++;
}
}else {
echo "Username <strong><u>$_POST[username]</u></strong> invalid ! <a href='1.php' >Click Here</a> ";
}
?>

There is no reason to assign the username and password variables in the way you did. Simply assign the post data to the variables as you normally would with a session.

Related

mysql redirect users to different pages based on role php

I need to redirect users to different pages based on the roles given to them in the database. Only the username and password is submitted on the login page. I have to fetch the role from the database which looks like this:
username | password | role
admin1 admin1 admin
alex12 alex12 (nothing to normal users)
Here is the code:
<?php
session_start();
// conectare la baza de date
$db = mysqli_connect("localhost", "root", "", "inregistrare");
if (isset($_POST['login_btn'])) {
$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$password = md5($password); // parola cryptata
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "Te poti Conecta!";
$_SESSION['username'] = $username;
header("location: clasa.php"); //spre o pagina
}else{
$_SESSION['message'] = "Parola gresita!";
}
}
?>
<head>
<title>Conectare</title>
<link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
if (isset($_SESSION['message'])) {
echo "<div id='error_msg'>".$_SESSION['message']."</div>";
unset($_SESSION['message']);
}
?>
<form method="post" action="clasa.php"> <!-- modifica si aici cand modifici mai sus la php-->
<table align="center">
<tr>
<th id="titlu" class="titlu" colspan="2">Conectare</th>
</tr>
<tr>
<td class="border">Username:</td>
<td class="border"><input type="text" name="username" class="text-input" size="20"></td>
</tr>
<tr>
<td class="border">Password:</td>
<td class="border"><input type="password" name="password" class="text-input" size="20"></td>
</tr>
<tr>
<td class="spatiu"></td>
<td class="spatiu"></td>
</tr>
<tr>
<td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
<td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
</tr>
</table>
</form>
</body>
</html>
You should check the user role. Here is an example how you can check it.
P.S the adminfile.php and anotherfile.php is where you should redirect the user and can be whatever you want.
if (mysqli_num_rows($result) == 1) {
$_SESSION['message'] = "Te poti Conecta!";
$_SESSION['username'] = $username;
$user = mysql_fetch_assoc($result);
if($user['role'] == 'admin'){
header("location: adminfile.php");
}else{
header("location: anotherfile.php");
}
}else{
$_SESSION['message'] = "Parola gresita!";
}
Use mysqli_fetch_row
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_row($result)) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
I can see that you've already got the answer from #leli.1337 But I thought I should give you same example in more secured way than the one you have above, bellow I'm using PDO prepared statements to prevent sql injections, and also There's no need to store success message /error message on a session variable.
Bellow is my code.
<?php
session_start();
// conectare la baza de date
$host_name = "localhost";
$u_name = "root";
$u_pass = "";
try {
$db = new PDO("mysql:host=$host_name;dbname=inregistrare", $u_name, $u_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex) {
error_log($ex);
}
$loginMessage = ""; //will fill this at a later stage.
if (isset($_POST['login_btn'])) {
$username = UserInput($_POST['username']);
$password = UserInput($_POST['password']);
try {
$stmt = $db->prepare("SELECT username,password, role FROM users where username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($result) > 1) { // username corerct
foreach ($result as $row) { // now lets validate password
if (password_verify($password, $row['password'])) {
$loginMessage = "<p style=\"color:green;\">Te poti Conecta!</p>"; //We don't really need to store the success on a session.
$_SESSION['username'] = $row['username'];
if ($row['role'] === "admin") {
//admin user
header("location:admin.php");
} elseif ($row['role'] === "") {
header("location: clasa.php"); //spre o pagina
}
} else {
// password incorrect
$loginMessage = "<p style=\"color:#f00\">Parola gresita!</p>";
}
}
}
}
catch (PDOException $e) {
error_log($e);
}
}
function UserInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<head>
<title>Conectare</title>
<link rel="stylesheet" type="text/css" href="./css/index-style.css">
</head>
<body>
<?php
echo $loginMessage;
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table align="center">
<tr>
<th id="titlu" class="titlu" colspan="2">Conectare</th>
</tr>
<tr>
<td class="border">Username:</td>
<td class="border"><input type="text" name="username" class="text-input" size="20"></td>
</tr>
<tr>
<td class="border">Password:</td>
<td class="border"><input type="password" name="password" class="text-input" size="20"></td>
</tr>
<tr>
<td class="spatiu"></td>
<td class="spatiu"></td>
</tr>
<tr>
<td><button class="register" type="submit" formaction="./register.php">Inregistrare</button></td>
<td><button class="connect" type="submit" name="login_btn">Conectare</button></td>
</tr>
</table>
</form>
</body>
</html>
As you can see I'm using password_verify() to verify the password hash instead of the md5 you used so, on your register.php page
you will need to hash the password like this:
$password = $_POST['password'];
// Now lets hash the password
$hash = password_hash($password, PASSWORD_DEFAULT);
instead of: $password= md5($_POST['password'];
So in your database you will store the $hash value
Thanks, Hope you find this more useful.

PHP Username and Password verification

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.

How to write one login form for both the admin and the user

I'm trying to write a code that takes two input values( username and password) and compare them with values in a table (named as user) in the database. Now, if the value inserted for the username is "admin" and also the password is "admin". I want to direct the admin to his page, and if the user has inserted his info, I want to direct him to his page also. My code below looks correct but I'm getting no response. How can this be fixed?
I wrote this code for html:
<form name="userLogin" action="LoginCode.php" method="POST" >
<h3>Login</h3>
<table width="450px">
<tr>
<td valign="top">
<label for="first_name">Your Name *</label>
</td>
<td valign="top">
<input type="text" name="user_username" maxlength="50" size="30" required>
</td>
</tr>
<tr>
<td valign="top">
<label for="last_name">Password *</label>
</td>
<td valign="top">
<input type="password" name="user_password" maxlength="50" size="30" required>
</td>
<tr>
<td></td>
<td><input type="submit" name="login" value="Login" required>
</td>
</tr>
</table>
</form>
And this is my LoginCode.php
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username = $_POST["user_username"];
$user_password = $_POST["user_password"];
/* $user_email=$_POST["user_email"]; */
if ($username = 'admin' and $user_password = 'admin') {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: ..Admin/AdminIndex.php");
} else {
$sql = ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if (!$result) {
echo "Error" . mysql_error();
} else {
$row = mysql_num_rows($result);
if ($row == 0) {
echo 'Invalid username or password';
} else {
$data = mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>
Check your if condition,
if ($username = 'admin' and $user_password = 'admin')
Here you are using single '=' i.e assignment operation instead of comparison i.e '=='.
Try this :
if ($username == 'admin' && $user_password == 'admin')
:::::::::::::::::::::::UPDATE:::::::::::::::::::::::::
What does this mean?
if ($username == 'admin' && $user_password == 'admin')
{
$data = mysql_fetch_array($result);
....
}
My point is without mysql_query() you are using mysql_fetch_assoc().
I fixed it !!
<?php
include ("../Connections/map_connection.php");
if (isset($_POST["login"])) {
$user_username= $_POST["user_username"];
$user_password= $_POST["user_password"];
if($user_username=='admin' && $user_password){
$sql= ("select * from admin where admin_username='$user_username' and admin_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['admin_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: ../Admin/AdminIndex.php");
}
}
}
else{
$sql= ("select * from user where user_username='$user_username' and user_password= '$user_password' ");
$result = mysql_query($sql);
if(!$result){
echo "Error".mysql_error();
}
else
{
$row= mysql_num_rows($result);
if($row==0) {
echo 'Invalid username or password';
}
else
{
$data= mysql_fetch_array($result);
session_start();
$_SESSION['name'] = $data['user_username'];
$_SESSION['start']=time();
$_SESSION['expire']= $_SESSION['start'] + 400;
header("location: UserIndex.php");
}
}
}
}
?>

PHP header not working on local server

Here is each one of my .php pages. I can get it to register and go onto my local server. However when I go to the login page and actually login it will not redirect to the members page. I am not sure what the issue it. I am pretty new to PHP and the code looks decent. Very simple but I am trying to get this to work. Any help is appreciated. Thanks.
config.php
<?php
$host = "localhost";
$username = "root";
$password = "root";
$db = "motofoto";
//Connect to MySQL Server
$con = mysqli_connect($host,$username,$password,$db) or die("Can not connect to Server.");
?>
Login.php
<?php
session_start();
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
if(isset($_SESSION['username'])){
header( "Location: members.php" ); //isset check to see if a variables has been 'set'
}
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "")
{
echo "Please fill in all the information!";
}
//Check to see if the username AND password MATCHES the username AND password in the DB
else
{
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user' and password = '$pass'") or die("Can not query DB.");
$count = mysqli_num_rows($query);
if($count == 1){
//YES WE FOUND A MATCH!
#$_SESSION['username'] = $user; //Create a session for the user!
header ("Location: members.php");
}
else{
echo "Username and Password DO NOT MATCH! TRY AGAIN!";
}
}
}
?>
<html>
<table>
<tr>
<form name="register" method="post" action="login.php">
<td>
<table>
<tr>
<td colspan="3"><strong><center>Login </center></strong></td>
</tr>
<tr>
<td>Username</td>
<td>:</td>
<td><input autofocus name="user" type="text" id="user"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="pass" type="password" id="pass"></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" name="submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<table>
<tr>
<td>Not a Member? Register</td>
</tr>
</table>
</html>
register.php
<?php
session_start(); //Must Start a session.
require "config.php"; //Connection Script, include in every file!
//Check to see if the user is logged in.
//'isset' check to see if a variables has been 'set'
if(isset($_SESSION['username'])){
header("location: members.php");
}
//Check to see if the user click the button
if(isset($_POST['submit']))
{
//Variables from the table
$user = $_POST['user'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];
//Prevent MySQL Injections
$user = stripslashes($user);
$pass = stripslashes($pass);
$rpass = stripslashes($rpass);
$user = mysqli_real_escape_string($con, $user);
$pass = mysqli_real_escape_string($con, $pass);
$rpass = mysqli_real_escape_string($con, $rpass);
//Check to see if the user left any space empty!
if($user == "" || $pass == "" || $rpass == "")
{
echo "Please fill in all the information!";
}
else
{
//Check too see if the user's Passwords Matches!
if($pass != $rpass)
{
echo "Passwords do not match! Try Again";
}
//CHECK TO SEE IF THE USERNAME IS TAKEN, IF NOT THEN ADD USERNAME AND PASSWORD INTO THE DB
else
{
//Query the DB
$query = mysqli_query($con,"SELECT * FROM members WHERE username = '$user'") or die("Can not query the TABLE!");
//Count the number of rows. If a row exist, then the username exist!
$row = mysqli_num_rows($query);
if($row == 1)
{
echo "Sorry, but the username is already taken! Try again.";
}
//ADD THE USERNAME TO THE DB
else
{
$add = mysqli_query($con,"INSERT INTO members (id, username, password) VALUES (null, '$user' , '$pass') ") or die("Can't Insert! ");
echo "Successful! <a href='members.php'> Click Here </a> to log In.";
}
}
}
}
?>
<html>
<table width="300" align="center" cellpadding="0" cellspacing="1" border="1px solid black">
<tr>
<form name="register" method="post" action="register.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong><center>Registration</center></strong></t
d>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="user" type="text" id="user"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="pass" type="password" id="pass"></td>
</tr>
<tr>
<td>Repeat Password</td>
<td>:</td>
<td><input name="rpass" type="password" id="rpass"></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" name="submit" value="Register"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
</html>
members.php
<?php
session_start();
require "config.php";
//Check to see if the user is logged in.
if(isset($_SESSION['username'])){
echo "Hello ".$_SESSION['username'].", you are logged in. <br /> This the member's page! Nothing here :(. <a href='logout.php'>Click Here </a>to log out.";
}
else{
echo "Please <a href='login.php'>Log In </a> to view the content on this page!";
}
?>
logout.php
<?php
session_start();
require "config.php";
session_destroy();
echo "You have successfully logged out. <a href='login.php'> Click here </a> to login!";
?>
1)try to add session close function, this may help as session is possibly not saved yet.
#$_SESSION['username'] = $user; //Create a session for the user!
session_write_close();
header ("Location: members.php");
2) And as Fred mentioned try to debug with php error reporting.
3) Small note: register.php => change link to Login.php not members.php
echo "Successful! <a href='Login.php'> Click Here </a> to log In.";
PS: I tested your script and it worked fine even without session_write_close();
Alternatively you can use following function to redirect through java script. It's not the solution but you can use as alternative.
function redirect($url)
{
echo $data= "<script type='text/javascript'> window.location.href = '".$url."'; </script>";
break;
}

php, login script

I am new in php and I am trying to write a registration script. My problem is that when I try to sign in and I can't see the user`s menu. Maybe the problem is with the sessions and cookies but I can't find it. Here is part of my code:
config.php
<?php
oB_start();
$con = mysql_connect("localhost","root","123");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("9gag", $con);
$logged = MYSQL_QUERY("SELECT * from users WHERE id='$_COOKIE[id]' AND password = '$_COOKIE[password]'");
$logged = mysql_fetch_array($logged);
?>
login.php
<?php
oB_start();
include("config.php");
if (!$logged[username]) {
if (!$_POST[login]) {
echo("<center><form method=\"POST\">
<table>
<tr>
<td align=\"right\">
User: <input type=\"text\" size=\"15\" maxlength=\"25\" name=\"username\">
</td>
</tr>
<tr>
<td align=\"right\">
Password: <input type=\"password\" size=\"15\" maxlength=\"25\" name=\"password\">
</td></tr><tr>
<td align=\"center\">
<input type=\"submit\" name=\"login\" value=\"Sign in\">
</td></tr><tr>
<td align=\"center\">
Sign up
</td></tr></table></form></center>");
}
if ($_POST[login]) {
$username = $_POST[username];
$password = $_POST[password];
$info = mysql_query("SELECT * FROM users WHERE username = '$username'") or die(mysql_error());
$data = mysql_fetch_array($info);
if($data['PASSWORD'] != $password) {
echo "Wrong username or password!";
}else{
$query = mysql_query("SELECT * FROM users WHERE username = '$username'") or die(mysql_error());
$user = mysql_fetch_array($query);
setcookie("id", $user['ID'],time()+(60*60*24*5), "/", "");
setcookie("password", $user['PASSWORD'],time()+(60*60*24*5), "/", "");
}
}
}
else {
echo ("<center>Welcome <b>$logged[username]</b><br /></center>
Profile<br />
Log out");
}
?>
How someone already said change COOCKIE With SESSION, i haven't understood very well your table/columns layout but i've tried to make better your code so try this :)
config.php
<?php
$con = mysql_connect("localhost","root","123");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("9gag", $con);
?>
login.php
<?php
session_start();
ob_start();
include("config.php");
if (!Isset($_SESSION['id'])) {
if (!$_POST['login']) {
echo '<center><form method="POST">
<table>
<tr>
<td align="right">
User: <input type="text" size="15" maxlength="25" name="username">
</td>
</tr>
<tr>
<td align="right">
Password: <input type="password" size="15" maxlength="25" name="password">
</td></tr><tr>
<td align="center">
<input type="submit" name="login" value="Sign in">
</td></tr><tr>
<td align="center">
Sign up
</td></tr></table></form></center>';
}
if ($_POST[login]) {
$username = $_POST['username'];
$password = $_POST['password'];
$info = mysql_query("SELECT * FROM users WHERE username = '".$username."'") or die(mysql_error());
$data = mysql_fetch_array($info);
if($data['password'] != $password) {
echo "Wrong username or password!";
}else{
$query = mysql_query("SELECT * FROM users WHERE username = '".$username."'") or die(mysql_error());
$user = mysql_fetch_array($query);
$_SESSION['username']=$user['username'];
$_SESSION['id']=$user['id'];
$_SESSION['password']=$user['password'];
}
}
}
else {
echo "<center>Welcome <b>".$_SESSION['username']."</b><br /></center>
<a href='editprofile.php'>Profile</a><br />
<a href='logout.php'>Log out</a>";
}
?>
The variable $logged is empty in the second file so !$logged will always be true, and the first part will always execute :) Use the cookie in the second file to see if it's logged or not

Categories