Why can't I get the login page to show up? - php

I have been working on this code for a while, but I am having an issue because the PHP I have before my HTML code for this login page is not working. Can someone look at this and tell me why logging in PHP code is tripping over itself? This code is above the Html code for the website paged "login.php".
<?php
session_start();
// Set the session cookie lifetime to 0
session_set_cookie_params(0);
$accounts = array(
'admin' => 'admin',
'publisher' => 'publisher',
'customer' => 'customer'
);
// Check if the user has submitted the login form
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Check if the username and password match an account
if (isset($accounts[$username]) && $accounts[$username] == $password) {
// Set the access level in the session
$_SESSION['access_level'] = $username;
// Redirect to the appropriate page
if ($username == 'admin') {
header('Location: EmployeeArray.php');
exit;
} else if ($username == 'publisher') {
header('Location: EmployeeArray.php');
exit;
} else if ($username == 'customer') {
header('Location: Products.php');
exit;
}
} else {
$error = 'Invalid username or password.';
}
}
// Check if the session is already set, and redirect to the login page if it is not
if (!isset($_SESSION['access_level'])) {
header('Location: login.php');
exit();
}
// Check if the user is logged in
if (isset($_SESSION['access_level'])) {
// User is logged in, show appropriate content
if ($_SESSION['access_level'] == 'admin') {
echo 'Welcome, admin! Log out';
} else if ($_SESSION['access_level'] == 'publisher') {
echo 'Welcome, publisher! Log out';
} else if ($_SESSION['access_level'] == 'customer') {
echo 'Welcome, customer! Log out';
}
} else {
// User is not logged in, show login form
?>

Assuming that the script above is part of login.php then calling the header function when testing !isset($_SESSION['access_level']) would be the cause of the infinite redirect. You could simply remove that logic test.
However the confusing part is why you allow users to return to the login page when they are logged in - the portion of code that begins if (isset($_SESSION['access_level'])) { displays the logout link but if the login is successful they should be redirected to another page ( Products.php or EmployeeArray.php ) and will not see this logout link. To remedy that the below code sets this HTML logout link in a session variable when the user successfully completes the login - that session variable can then be used on the page to which they are redirected.
I tested the following and it all seemed to work but I might have missed the point somewhere.
<?php
#login.php
error_reporting( E_ALL );
# call this **before** you start the session!
session_set_cookie_params(0);
session_start();
# If the user is logged in, redirect to the appropriate location
if( isset( $_SESSION['access_level'], $_SESSION['redirect'] ) ) {
exit( header( sprintf('Location: %s', $_SESSION['redirect'] ) ) );
}
# process the POST request
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['username'],
$_POST['password']
)){
$accounts = array(
'admin' => 'admin',
'publisher' => 'publisher',
'customer' => 'customer'
);
$username = $_POST['username'];
$password = $_POST['password'];
# Supplied username/password is in accordance with the $accounts array
if( isset( $accounts[ $username ] ) && $accounts[ $username ] == $password ) {
switch( $accounts[ $username ] ){
case 'admin': $location='EmployeeArray.php'; break;
case 'publisher': $location='EmployeeArray.php'; break;
case 'customer': $location='Products.php'; break;
}
# set some useful session variables
$_SESSION['access_level']=$accounts[ $username ];
$_SESSION['html_logout']=sprintf('Welcome, %s! Log out', $_SESSION['access_level'] );
$_SESSION['redirect']=$location;
exit( header( sprintf('Location: %s', $location ) ) );
} else {
$_SESSION['error'] = 'Invalid username or password.';
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>login</title>
</head>
<body>
<?php
if( !empty( $_SESSION['error'] ) ){
printf('<h1>%s</h1>', $_SESSION['error'] );
unset( $_SESSION['error'] );
}
?>
<form method='post'>
<label>Username<input type='text' name='username' /></label>
<label>Password<input type='password' name='password' /></label>
<input type='submit' />
</form>
</body>
</html>
And the various other scripts:
<?php
session_start();
$script='EmployeeArray.php';
printf(
'<h1>%s - %s</h1>
<p>%s</p>',
$script,
$_SESSION['access_level'],
$_SESSION['html_logout']
);
?>
<?php
session_start();
$script='Products.php';
printf(
'<h1>%s - %s</h1>
<p>%s</p>',
$script,
$_SESSION['access_level'],
$_SESSION['html_logout']
);
?>
<?php
#LogoutQuestion.php
session_start();
$_SESSION = array();
if( ini_get("session.use_cookies") ) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"],
$params["domain"],
$params["secure"],
$params["httponly"]
);
}
session_destroy();
exit( header('Location: login.php') );
?>

Related

header function not redirecting to home.php, why?

Here i am using header function to redirect to home.php after login, but header function is not redirecting to that page. Even when i run same code on my local computer it works fine.
<?php
ob_start();
session_start();
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
$error = false;
if( isset($_POST['btn-logIn']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$pass = trim($_POST['password']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$errMsg = "Please enter valid email address.";
}
// if there's no error, continue to login
if (!$error) {
$res=mysql_query("SELECT userId, userfName, userlName,userPassword FROM userdata WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row
if( $count == 1 && $row['userPassword']==$pass ) {
$_SESSION['user'] = $row['userId'];
header("Location:home.php");
} else {
$errMsg = "Try again...";
}
}
}
?>
You do not need the !="" on line 5 because isset() already checks for existence. Either its there or its not.
if (isset($_SESSION['user'])){
header("Location: home.php");
exit;
} else {
echo "something here";
}
You can use !isset() to get the opposite result as well.
Try your code with this code,
<?php
ob_start();
session_start();
if ( isset($_SESSION['user'])!="" ) {
header("Location:home.php");
exit;
}
require_once 'phpconnection.php';
// it will never let you open index(login) page if session is set
?>

Can't get login success to view

so I've put in the write credentials to the login form, and it's supposed to redirect me to the home.php page which displays a successful login, however when I hit submit, the page just refreshes and doesn't do anything. If I change what the login_action loads after login it does it right, but then if I tell it to load home.php it just does nothing....Any Help?
Here's my home.php code:
<?php
session_start() ;
if( !isset($_SESSION['username']))
{
require('login_tools.php');
load();
}
$page_title = 'Home';
echo"<h1>HOME</h1>
<p>You are now logged in, {$_SESSION['username']}</p>";
echo'<p>Logout</p>';
?>
and the login_action.php
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
require ('../connect_db.php') ;
require ('login_tools.php') ;
list ($check, $data) =
validate($dbc, $_POST['username'], $_POST['password']);
if ($check )
{
session_start() ;
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
load('home.php') ;
}
else {$errors = $data ;}
mysqli_close( $dbc);
}
include('login.php');
?>
**login.php:**
<?php
$page_title = 'Login';
if ( isset( $errors ) && !empty( $errors))
{
echo'<p id="err_msg">Oops! There was a problem:<br>';
foreach ( $errors as $msg )
{
echo " - $msg<br>";
}
echo 'Please try again or Register</p>';
}
?>
<h1>Login</h1>
<form action="login_action.php" method="POST">
<p>
Username: <input type="text" name="username">
</p><p>
Password: <input type="password" name="password">
</p><p>
<input type="submit" value="Login" >
</p>
</form>
According to your code it is supposed to refresh. Indeed, it is not a refresh, it is the infinite loading of login.php by include it in the end of login_action.php
You should use header redirect instead of including as follows:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
if ( $_SERVER['REQUEST_METHOD'] == 'POST')
{
require ('../connect_db.php') ;
require ('login_tools.php') ;
list ($check, $data) =
validate($dbc, $_POST['username'], $_POST['password']);
if ($check )
{
session_start() ;
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
$extra = 'home.php';
header("Location: http://$host$uri/$extra");
exit;
}
else {
$errors = $data ;
$_SESSION['Errors'] = $errors;
$extra = 'login.php';
header("Location: http://$host$uri/$extra");
exit;
}
mysqli_close( $dbc);
}
?>
In login.php
$page_title = 'Login';
if ( isset( $_SESSION['Errors'] ) && !empty( $_SESSION['Errors'])){
$errors = $_SESSION['Errors'];
//continue your code...
// at the end of the code:
unset($_SESSION['Errors']);
Based on your reply, i guess session doesn't get anything to load home. It is from:
$_SESSION['user_id'] = $data['user_id'] ;
$_SESSION['username'] = $data['username'] ;
this makes validate get unvalidated to send the session.
Try to change the $data into variables, as follows:
$_SESSION['user_id'] = $user_id ;
$_SESSION['username'] = $username ;
to show the message, you can use meta refresh to encertain that it really sends the login data.
If this not works, there must be something wrong with the grabbing data from the connection.
<?php # LOGIN HELPER FUNCTIONS.
# Function to load specified or default URL.
function load( $page = 'login.php' )
{
# Begin URL with protocol, domain, and current directory.
$url = 'http://' . $_SERVER[ 'HTTP_HOST' ] . dirname( $_SERVER[ 'PHP_SELF' ] ) ;
# Remove trailing slashes then append page name to URL.
$url = rtrim( $url, '/\\' ) ;
$url .= '/' . $page ;
# Execute redirect then quit.
header( "Location: $url" ) ;
exit() ;
}
# Function to check email address and password.
function validate( $dbc, $email = '', $pwd = '')
{
# Initialize errors array.
$errors = array() ;
# Check email field.
if ( empty( $email ) )
{ $errors[] = 'Enter your email address.' ; }
else { $e = mysqli_real_escape_string( $dbc, trim( $email ) ) ; }
# Check password field.
if ( empty( $pwd ) )
{ $errors[] = 'Enter your password.' ; }
else { $p = mysqli_real_escape_string( $dbc, trim( $pwd ) ) ; }
# On success retrieve user_id, first_name, and last name from 'users' database.
if ( empty( $errors ) )
{
$q = "SELECT user_id, first_name, last_name FROM users WHERE email='$e' AND pass=SHA1('$p')" ;
$r = mysqli_query ( $dbc, $q ) ;
if ( #mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array ( $r, MYSQLI_ASSOC ) ;
return array( true, $row ) ;
}
# Or on failure set error message.
else { $errors[] = 'Email address and password not found.' ; }
}
# On failure retrieve error message/s.
return array( false, $errors ) ;
}

Restrict a content using session control in php

Hello reading websites and forums i have learned that, content can be prevented using sessions.I have a index.php page which checks sessions and give results as per the condition:
<?php
session_start();
if( $_SESSION['user'] != $name ) { echo "Sorry,no session found or is expired";
require( 'login.php' );
}
else {
echo "hello,you have session existing";
}
?>
I have table created details
FNAME
LNAME
BDAY
PASS
EMAIL
CODES
login.php is as follows:
<?php
$name = $_POST['name'];
$pass = $_POST['pass'];
mysql_connect('mysqlhost','user','pass','userdatabase');
$query=mysql_query(sprintf("SELECT FNAME FROM `details` WHERE FNAME=$name AND PASS=$pass";
mysql_real_escape_string($PASS)));
if($query) { while($row = mysql_fetch_assoc($query)) { $rows[1] = $row; } }
if( isset($name) || isset($pass) )
{
if( empty($name) ) {
die ("ERROR: Please enter username!");
}
if( empty($pass) ) {
die ("ERROR: Please enter
password!");
}
if( $name == $rows[1][FNAME] &&
$pass == $rows[1][PASS] )
{
session_start();
$_SESSION['user'] = $_POST['name'];
header('Location: index.php');
}
else {
echo "ERROR: Incorrect username
or password!";
}
}
else {
?>
<html>
<head>
<body>
//Load login form here & save $SESSION value in "name"
</html>
<?php } ?>
So,my code is going wrong somewhere and cannot see "hello,you have session existing".Any help again would be gratefull.(Code can be half viewed, sorry for that)
Try this -
if( !isset( $_SESSION[ "user" ] ) )
instead of
if( $_SESSION['user'] != $name )
In login.php you must somehow pass the value of $_POST['name'] as $name to index.php, and also it's really a bad idea to put session as password, few tips:
1) use a user id, say 1,2,3... and add a primary key to it, and use that id to do stuff like granting access.
2)md5 your pass while registering, and check it like
if (md5($_POST['pass']) == $pass) {
//some code
};

Session Start and Stop Error 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.

php sessions to authenticate user on login form

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.
what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}
Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.
Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!
The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}
Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}

Categories