Session Start and Stop Error Php - php

Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
include('login_helper.php');
?>
<!--
html form
-->
Login/Logout Links depending on session state:
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
require_once('login_helper.php');
/*
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['userid'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
*/
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
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);
$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 the user has not logged in
if(!isLoggedIn())
{
echo "<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
die();
}
?>
login_helper.php
<?php
function validateUser()
{
#session_regenerate_id (); //this is a security measure
$_SESSION['valid'] == 1;
$_SESSION['uID'] = $userid;
echo "Session made";
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
function logout()
{
session_start();
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "
<html>
<head>
<meta http-equiv='refresh' content='0'; url=index.php'>
</head>
<body>
</body>
<html>";
}
?>
pwhome.php
<?php
session_start();
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
logout.php
<?php
require_once('login_helper.php');
logout();
?>
Current State: When I visit index.php and login with credentials that are indeed correct, I get a never ending refresh of check_buyer.php
How do I get this to login in properly (from index.php) and redirect me properly to pwhome.php upon providing valid credentials on index.php ?

I wonder with your code, if you want to logout and refresh the index.php with new session value, why dont you put header( 'Location: index.php' ); in your logout function?
So, i think this probably will help, modify your logout.php:
Logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
echo "logged out?";
header( 'Location: index.php' );
}
logout();
?>
Last Edited :
Try this codes :
Index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<!--
html form
-->
<?php
if($_SESSION['valid'] == 1){
echo "<a href='logout.php'>Logout</a>";
echo 'userID '.$userid;
}
else{
echo "<a href='index.php'>Login</a>";
}
?>
check_buyer.php
<?php
session_start(); #recall session from index.php where user logged include()
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
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);
$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 the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $userid;
}
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
return true;
return false;
}
?>
logout.php
<?php
session_start();
function logout()
{
$_SESSION = array(); //destroy all of the session variables
session_destroy();
header( 'Location: index.php' );
}
logout();
?>

Instead of
header('Location: index.php');
Try meta refresh for page forwarding. After closing the php block, add some HTML code like;
<html>
<head>
<meta http-equiv="refresh" content="0; url=index.php">
</head>
<body>
</body>
<html>
Sometimes session doesn't work as it should when you use header() function for page forwarding.

Related

After Logout don't navigate to the page visited before

How to create a session variable, and once logout is successful no need to navigate to the page that is visited before.
The Login.php and logout.php pages are provided below:
Login.php
require( 'dbConfig.php');
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["userid"];
if ($name == '' ) {
$msg = "You must enter all fields";
}
else
{
$sql = "SELECT * FROM user WHERE userid = '$name' ";
$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['userid'] = $name;
header('Location: teams.php');
exit;
}
$msg = "Username do not match";
}
}
?>
Logout.php
<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}
?>
ISSUE : After successful logout the page is navigating to the page visited before.
Any help is appreciated, thanks in advance.
In your logout.php page, instead of if condition, simply write:
session_destroy();
So your page code would be :
<?php
session_start(); // not compulsory to write
session_destroy();
?>

header location url not working in ipage

I have built a login page for the admin panel,after succesful login the page will redirect to the dashboard.php.When am running in localhost it is working fine,session also working.But when I uploaded in Ipage the page is not redirecting,it is simply reloading the login page.
My session code is
<?php
session_start();
if(isset($_SESSION['user']) && isset($_SESSION['pass']))
{
header('Location: dashboard.php');
}
?>
The validation code and redirecting code
<?php
//session_start();
function login($username, $password)
{
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysql_query($query)or die(mysql_error());
$num_row = mysql_num_rows($result);
if( $num_row == 1 )
{
while( $row=mysql_fetch_array($result) )
{
return true;//$_SESSION['userid'] = $row['userid'];
}
} else {
return false;
}
return true;
}
include("connect.php");
if (isset($_REQUEST['login'])){
$validLogin = login($_REQUEST['user'], $_REQUEST['pass']);
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
echo 'hi there';
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
}
?>
<?php
ob_start();
?>
at first of line
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
exit;
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
You can't do an echo after your header() . Uncomment it and add an exit as shown below.
if ($validLogin)
{
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
//echo 'hi there'; //<------ Commented this
exit;// <---- Added exit
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
Remove space after Location: and try following code
header("Location:dashboard.php");
Try using ob_clean
if ($validLogin)
{
ob_clean();// <---- Added this
$_SESSION['user'] =$_REQUEST['user'];
$_SESSION['pass'] = $_REQUEST['pass'];
header("Location: dashboard.php");
//echo 'hi there'; //<------ Commented this
exit;// <---- Added exit
} else
{
echo "<font color='white'><h1> Incorrect Details,Entry Prohibited :) </h1></font> ";
}
Edit: according to your comments on other posts, you disabled the session.. make sure it's enabled, both on login and dashboard page

Get user's ID from mysql UPON login and echo to screen php/mysql

login/index.php
<?php
session_start();
require_once('../inc/db/dbc.php');
?>
<?php
if($_SESSION['valid'] == 1){ #user has logged in by creating a session var
echo "<a href='logout.php'>Logout</a>";
}
else{
return false;
}
?>
Once login/index.php is filled out, it validates a valid login with 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;
$_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 a valid user is provided, it redirects to buyer/index.php which includes the buyer_profile.php page (farther below):
<?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>";
}
?>
buyer_profile.php
Which is basic HTML with the session_start(); at the first line
The problem lies in login/buyer/index.php, where echo 'buyerid: '.$_SESSION['uID']; does not display anything. It should be outputting the uID of the user logged in from the SELECT query in the login/check_buyer.php why isn't it storing this value upon logging in??
Anyone??
Perhaps the SELECT query is returning false so $ifUserExists is not having any value set to it (other than false).
You can test this by using print_r($ifUserExists);, which will print out the array if it is a set and valid array; otherwise, it will not print anything.
You can also try this code, that I think might solve the problem.
list($ifUserExists) = ($result) ? #array_values(mysqli_fetch_assoc($result)) : NULL;
$_SESSION["uID"] = ($ifUserExists && $ifUserExists["uId"]) ? $ifUserExists["uId"] : NULL;
# insert your couple other lines of code here, I will not write them to save space
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}
elseif ($_SESSION["uID"]) {
validateUser();
}
else {die("error!");}

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

PHP session problems

I have a login page and a 'member's area' page, the login code is here:
login.php
if ($account->is_logged_in())
{
$route->to(ACCOUNT_URL);
}
elseif (isset($_POST['username']))
{
if ($account->authenticates())
{
if ($account->log_in()) $route->to(ACCOUNT_URL);
}
else
{
$flash->set('error', 'The credentials you provided are incorrect.');
}
}
the functions (in a different file)
public function log_in ()
{
session_unset();
session_destroy();
if(session_start())
{
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $_POST['username'];
}
}
public function authenticates ()
{
$username = $_POST['username'];
$password = $_POST['password'];
if (ctype_alnum($username) && ctype_alnum($password))
{
$username = mysql_real_escape_string(filter_var($username, FILTER_SANITIZE_STRING));
$password = $this->encrypt(mysql_real_escape_string(filter_var($password, FILTER_SANITIZE_STRING)));
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Then my members area page:
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
login.php redirects me (meaning it authenticates my account), but when I get to members.php it echoes out 'not logged in' and that is all.
You'll need to call session_start() at the top of members.php (and any page that needs to access the $_SESSION.
// Must initiate the session to test if logged in.
session_start();
if ($account->is_logged_in())
{
echo 'logged in';
}
elseif (!$account->is_logged_in())
{
echo 'not logged in';
echo session_id();
print_r($_SESSION['logged_in']);
}
Do you have session_start() at the very beginning of all scripts which use sessions?

Categories