why is my error message not showing if password or username is incorrect? i would like an error message displayed if the user enters the wrong username or password
code can be seen below
<?php
// Inialize session
session_start();
// Include database connection settings
include('connect.inc');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM users WHERE (username = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['password'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
}
else
{
// Invalid login
echo "Your username or password are incorrect!";
}
// Jump to secured page
$row = mysql_fetch_array($login);
switch ($row['drop']):
case yes:
header('Location: choose1.php');
exit;
case no:
header('Location: choose2.php');
exit;
}
else {
header('Location: login.php');
}
?>
write case value in ' also break in switch case
case 'yes':
header('Location: choose1.php');
exit; // this line shouldn't be needed but it's good practice
break;
case 'no':
header('Location: choose2.php');
exit;
break;
better way:
<?php session_start();
require_once('connect.inc');
// Retrieve username and password from database according to user's input
$input_username = mysql_real_escape_string($_POST['username']);
$login = mysql_query("SELECT * FROM users WHERE username = '".$input_username."'" );
// Check username and password match
$row = mysql_fetch_array($login);
if (mysql_num_rows($login)) {
if($row['password'] === md5($_POST['password'])){
$_SESSION['username'] = $_POST['username']; // store in session
switch ($row['drop']){
case 'yes': header('Location: choose1.php'); break;
case 'no': header('Location: choose2.php'); break;
}
exit;
}
else {
echo "Wrong username and password combination";
exit;
}
}
else{
// Invalid login
echo "Invalid Unsername";
header('Location: login.php');
exit;
}
?>
<?php
// Inialize session
session_start();
// Include database connection settings
include('connect.inc');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM users WHERE (username = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['password'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
}
else {
// Invalid login
header('Location: login.php?try=failed');
exit;
}
// Jump to secured page
$row = mysql_fetch_array($login);
switch ($row['drop']) {
case 'yes': header('Location: choose1.php'); exit;
case 'no': header('Location: choose2.php'); exit;
}
?>
On login.php, check for try=failed:
if ($_GET['try'] === 'failed') {
echo "Your username or password are incorrect!";
//echo YOUR_LOGIN_FORM here
}
Probably a better way to handle your problem.
Note: I initialize a $_SESSION['error'], just use an if(isset($_SESSION['error'])) echo $_SESSION['error']; on your login.php to display the error.
// Inialize session
session_start();
// Include database connection settings
include('connect.inc');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM users WHERE (username = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . md5($_POST['password']) . "')");
// Check username and password match
if(mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// fetch results
$row = mysql_fetch_array($login);
// jump to secured page
switch($row['drop'])
{
case 'yes':
header('Location: choose1.php');
exit;
case 'no':
header('Location: choose2.php');
exit;
}
} else {
// invalid login
// set error session
$_SESSION['error'] = "Your username or password are incorrect!";
header('Location: login.php');
exit;
}
?>
Related
PHP session value lost after header redirection in php
Our code
Login.php
<?php
session_start();
include('./includes/variables.php');
include_once('includes/custom-functions.php');
$fn = new custom_functions;
if (isset($_POST['btnLogin'])) {
// get username and password
$username = $db->escapeString($fn->xss_clean($_POST['username']));
$password = $db->escapeString($fn->xss_clean($_POST['password']));
// set time for session timeout
$currentTime = time() + 25200;
$expired = 3600;
// create array variable to handle error
$error = array();
// check whether $username is empty or not
if (empty($username)) {
$error['username'] = "*Username should be filled.";
}
// check whether $password is empty or not
if (empty($password)) {
$error['password'] = "*Password should be filled.";
}
// if username and password is not empty, check in database
if (!empty($username) && !empty($password)) {
// change username to lowercase
$username = strtolower($username);
//encript password to sha256
//$password = md5($password);
// get data from user table
$sql_query = "SELECT * FROM admin WHERE username = '" . $username . "' AND password = '" . $password . "'";
$db->sql($sql_query);
/* store result */
$res = $db->getResult();
// print_r($res);
// die();
$num = $db->numRows($res);
// Close statement object
if ($num == 1) {
$_SESSION['id'] = $res[0]['id'];
$_SESSION['role'] = $res[0]['role'];
$_SESSION['user'] = $username;
$_SESSION['timeout'] = $currentTime + $expired;
//print_r($_SESSION);
//die();
header("location: home.php");
exit();
} else {
$error['failed'] = "<span class='label label-danger'>Invalid Username or Password!</span>";
}
}
}
?>
Home.php
<?php session_start();
print_r($_SESSION);
?>
Output :
array()
We tried the following method
Made sure session_start(); is called before any sessions are
being called
After the header redirect, end the current script using exit();
Made sure cookies are enabled in the browser we were using to test
it on.
Made sure didn't delete or empty the session
Made sure file extension is .php
You have to include you file in which you have initialized session
For example
first file named phpcodeonly.php:
session_start() //put it in start
if(login success){
$_SESSION['email']= $email
}
your other file.php:
include 'phpcodeonly.php'; //on top
<h1> Welcome <?php echo $_SESSION['email']?> </h1>
I am currently working on a login page on wich i want the user to be redirected to another page if a boolean read from the database is set on true.
However, the header() in this if statement never redirects the user properly.
here is a sample of my code:
<?php
session_start();
include_once 'php/dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$gebruikersnaam = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $gebruikersnaam. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
if($row['initialised'] == true)
{
header("Location: dashboard.php");
exit();
}
else{
$_SESSION['usr_name'] = $row['username'];
$_SESSION['usr_company'] = $row['companyname'];
header("Location: starter-page.php");
exit();
}
} else {
$errormsg = "Incorrect Email or Password!";
}
}
?>
If i put the if condition on false. The second header with "location: strater-page.php" will redirect to the correct page.
I do not have any unnecessary whitespace.
Puttin:
error_reporting(E_ALL);
ini_set('display_errors', 1);
In the code doesn't show anything.
I am not outputting anything before the header...
Am i missing something?
try redirect using script
<?php
if($row['initialised'] == true)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='dashboard.php';
</SCRIPT>");
}
?>
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 have made a simple login script here.
There are 3 files, 1 is functions.php(Containing the login function), then there is userdashboard.php, which contains some user functions and then another file users.php which processes the login.
The problem is, whenever I login, the login in successful but it throws the error :- unknow variable username.
It should display the username of the person logged in, what am I doing wrong ?
Here's the code :-
functions.php
<?php
include 'dbconnector.php';
function checklogin($username,$password)
{
include 'dbconnector.php';
$userexists=false;
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$userexists=true;
}
else
{
$userexists=false;
}
return $userexists;
}
userdashboard.php
<?php
include('dbconnector.php');
session_start();
if(isset($_SESSION['logged']) && $_SESSION['logged']=1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
else
{
header('Location:login.php');
}
echo 'logout';
?>
file where login is processed.
include 'functions.php';
.
.
.
case 'login':
$username=$_POST['username'];
$password=$_POST['password'];
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
if((!empty($username)) && (!empty($password)))
{
if(!checklogin($username,$password))
{
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
}
else
{
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
}
}
else
{
echo "username or password fields cannot be empty, redirecting";
header('refresh:2;URL=login.php');
}
break;
Thanks for the fix Houssni.
I have a weird error here.
Even if I try a valid combination of username and password, it always goes to the else part and throws the error.
What wrong am I doing here ?
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
session_start();
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
exit();
}
else
{
echo mysql_num_rows($result);
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
exit();
}
$username is a parameter so you can only use it in its function scope.
Get the username by $_POST or set the $_SESSION in that function.
Or in userdashboard.php you should assign the variable $username again and give its value.
And in functions.php you have another include inside this function. You are including this file twice if you call this function.
And in the end of where you call you header("Location: ") you should call exit() because else it will keep running the PHP code of that page.
There is another error in your userdashboard.php
change
if(isset($_SESSION['logged']) && $_SESSION['logged']=1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
To
if(isset($_SESSION['logged']) && $_SESSION['logged']==1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
session_start() function need to include in condition section,
if((!empty($username)) && (!empty($password)))
{
if(!checklogin($username,$password))
{
session_start(); // added session start
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
exit();
}
else
{
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
exit();
}
}
I am creating a login system for my website. I want to grab the user's userID (aka a primary key out of the database) to use when they log in.
I have 3 files I'm using:
/index.php - that is basically the login form with a username and password fields. It contains this php code:
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
Once form is submitted, it goes to check_buyer.php (/check_buyer.php)
<?php
session_start(); #recall session from index.php where user logged
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
#header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return true;
}
function validateUser() {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = (isset($ifUserExists['uID'])) ? $ifUserExists['uID'] : null;
echo 'sessuID: '.$_SESSION['uID'];
$_SESSION['uUserType'] = 1; // 1 for buyer - 2 for merchant
}
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
If the credentials are valid, the user is sent to login_new/buyer/index.php
<?php
session_start();
if($_SESSION['uUserType'] != 1) // error
{
die("
<div class='container_infinity'>
<div class='container_full' style='position:static;'>
<img src='img/error/noAccess.png' style='float:left;' /> <br />
<h2>403 Error: You may not view this page. Access denied.</h2>
</div>
</div>
");
}
function isLoggedIn()
{
return ($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: ../index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1 && $_SESSION['uUserType'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
echo 'buyerid: '.$_SESSION['uID'];
require_once('buyer_profile.php');
}
else{
echo "<a href='../index.php'>Login</a>";
}
?>
The problem is, when I login with valid credentials it sends me to login_new/buyer/index.php with the account, but is not outputting the buyer ID using the code echo 'buyerid: '.$_SESSION['uID']; what am I doing wrong here?
Try commenting the header() redirect and echo the $_SESSION['uID'] right after you set it in function validateUser() to see if the session data is actually set right there