$_SESSION not working correctly - php

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();
}
}

Related

php header in if statement not working

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>");
}
?>

acessing a php page only when a different php page directs to it

After submiting username and password in connect.php, user reaches contentselect.php .But if a user enters url like localhost/users/contentselect.php he is still able to see the contentselect.php page,which he should not see because he has not entered username and password in connect.php
//connect.php
<?php
Include ('mysql.php');
session_start();
if (isset($_POST['name'], $_POST['password']))
{
$name = $_POST['name'];
$password = $_POST['password'];
$password = md5($password);
$result = mysql_query("SELECT name,password FROM project WHERE name='" . $name . "' AND password='" . $password . "'");
if (mysql_num_rows($result) > 0)
{
$_SESSION['logged_in'] = true;
$_SESSION["name"] = $name;
header('Location:contentselect.php');
exit();
}
else
{
echo "wrong password or username";
}
}
?>
//this is contentselect.php
<?php
session_start();
echo "Hello ".$_SESSION["name"]."!";
?>
Keeping in mind everything #Fred-ii mentioned, This should work:
<?php
session_start();
if(isset($_SESSION['logged_in']))
{
echo "Hello ".$_SESSION["name"]."!";
}
else{
echo "Sorry Charlie";
}
?>
Or you could use cookies too!
Ofcourse you would have to set the cookies first and then unset it in your signout.php page.
login.php
if($user == $user_db && $pass == $pass_db)
{
$Month = 86400 + time();
setcookie('name', $user, $Month);
exit(header("Location:index.php"));
}
signout.php
if(isset($_COOKIE['name']))
{
unset($_COOKIE['name']);
setcookie('name', '', time() - 3600, 'login.php');
setcookie('name', '', time() - 3600, 'signup.php');
echo "<script type='text/javascript'>alert('YOU HAVE LOGED OUT!')</script>";
}
exit(header("refresh:1; url=welcome.php"));
You need to check that the user is logged in on the contentselect.php page, so you'd need to change that page to something like this:
//this is contentselect.php
<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
header('Location: connect.php');
exit();
}
echo "Hello ".$_SESSION["name"]."!";
?>

PHP script reports wrong credentials

Ok, this is my code for authentication. For now, i have one table and 5 PHP working scripts except this one. After successful login, user should be redirected to his home page, but the problem is, PHP echoes "Cannot login" error message regardless of login details. Heres the script:
session_start();
include_once'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header ("Location: home.php");
}
if (isset($_POST['login'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = mysql_query("SELECT * FROM users WHERE email='".$email."'");
$num = mysql_fetch_assoc($sql);
if ($num['password'] == $pass)) {
$_SESSION['user'] = $num['user_id'];
header ("Location: home.php");
}
else {
echo "Cannot login";
}
}
Any hints ? Thank you
session_start();
include_once'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header ("Location: home.php");
}
if (isset($_POST['login'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = mysql_query("SELECT * FROM users WHERE email='".$email."'");
$num = mysql_fetch_assoc($sql);
if(count($num)>0){
if ($num['password'] == $pass)) {
$_SESSION['user'] = $num['user_id'];
header ("Location: home.php");
}
else {
echo "Cannot login";
}
}else{
echo "Cannot login, email id not found";
}
}
Make sure you are getting password from the data base.
1.I think Your password encrypted in db.
2.Check it out it may be md5,sha etc.
3.If yes. Change Like this
if ($num['password'] == md5($pass)){
.
.
.
.
}
Hope It Helps..

error message not showing on password fail

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;
}
?>

Get values of userAccount upon Login

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

Categories