Action script for login form not working - php

having problems understanding why my script to login will not work, so its a simple login script that checks the users and fields as expected yet when it does the logic it does not seem to be loggin in the users :S
action script:
<?php
if ( $SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
require ( 'connect_db.php' );
require ( 'login_tools.php' );
list ( $check , $data ) =
validate ( $dbc , $_POST[ 'email' ] , $_POST [ 'pass' ] ) ;
if ( $check )
{
session_start() ;
$_SESSION[ 'user_id' ] = $data [ 'user_id' ] ;
$_SESSION[ 'first_name' ] = $data [ 'first_name' ] ;
$_SESSION[ 'last_name' ] = $data [ 'last_name' ] ;
load ('home.php');
}
else { $errors = $data ; }
mysqli_close( $dbc );
}
?>
An action script to process the login:
<?php
function load( $page = 'login.php')
{
$url = 'http://' . $SERVER['HTTP_HOST'] .
dirname( $_SERVER ['PHP_SELF'] );
$url = rtrim( $url , '/\\' );
$url = '/' . $page ;
header ( "location: $url" );
exit();
}
function validate( $dbc , $email = ',$pwd = ')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.' ; }
else
{ $e = mysqli_real_escape_string( $dbc , trim( $email ) ) ; }
if (empty($pwd))
{ $errors[] = 'Enter your password.' ; }
else
{ $e = mysqli_real_escape_string( $dbc , trim( $pwd ) ) ; }
if ( empty( $errors ) )
{
$q = "SELECT user_id, first_name, last_name FROM users WHERE enail = '$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 );
}
else
{
$errors[] = 'Email address and password not found.' ;
}
return array( false , $errors) ; }
}
?>
And it will land here...
<?php
session_start();
if ( !isset( $_SESSION[ 'user_id' ] ) )
{
require ( 'login_tools.php' ) ;
load() ;
}
$page_title = 'Home' ;
echo'<p>
logout
</p> ';
?>
The login script tried to execute login_action.php but dosnt move from there...I have no syntax errors though?

You misspelled $_SERVER variable - there is not such thing like $SERVER
EDIT
login_tools.php
function validate($dbc, $email = ',$pwd = ')
should be:
function validate($dbc, $email = '' , $pwd = '')
next:
$e = mysqli_real_escape_string($dbc, trim($pwd));
should be:
$p = mysqli_real_escape_string($dbc, trim($pwd));
and return statement move after if statement:
if (empty($errors)) {
...
}
return array(false, $errors);
I hope that you're playing around with PHP or something, beacuse this is really bad code. But you know that, right?

Ok so I found a new script to see if I can see if it its a problem with the database, table or the script - Heres the new script:
Login.php
<h1>Login</h1>
<form action="login_action.php" method="POST">
<p>
Email Address: <input type="text" name="email" />
</p><p>
Password: <input type="password" name="pass" />
</p><p>
<input type="submit" value="login" />
</p>
</form>
checklogin.php
<?php
include ('connect_db.php');
$myemail=$_POST['email'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myemail = stripslashes($myemail);
$mypassword = stripslashes($mypassword);
$myemail = mysql_real_escape_string($myemail);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT user_id, email, first_name, last_name FROM users WHERE email='$myemail' and pass='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("email");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong email or Password";
}
?>
login_success.php
<?php
session_start();
if(!session_is_registered(email)){
header("location:login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
The error I get now is the email or password is wrong? I know that it isnt...

Related

Error In Session With Login Scripts

I'm receiving the error Error In Session when I run my login script:
session_start();
if (isset($_POST['login'])) {
$logusername=$_POST['username'];
$logpassword=sha1(md5($_POST['password']));
$redirectLoginSuccess = "dashboard.php";
$result=mysqli_query($con, "SELECT * FROM users WHERE username='$logusername' AND password='$logpassword'")or die('Error In Session');
$row=mysqli_fetch_array($result);
if($result>0){
$access = mysqli_fetch_assoc($result,0,'access');
$userID = mysqli_fetch_assoc($result,0,'id');
$username = mysqli_fetch_assoc($result,0,'username');
$name = mysqli_fetch_assoc($result,0,'name');
//declare two session variables and assign them
$_SESSION['username'] = $username;
$_SESSION['userID'] = $userID;
$_SESSION['name'] = $name;
$_SESSION['access'] = $access;
}
header("Location: " . $redirectLoginSuccess );
}
I receive this error everytime I run the script not sure exactly where the error is.
The code below works but for some reason, I am not able to echo the session variable name. Is it possible that the session variable not being stored?
if ( isset( $_POST[ 'login' ] ) ) {
$errMsg = '';
// Get data from FORM
$username = $_POST[ 'username' ];
$password = sha1($_POST[ 'password' ]);
if ( $username == '' )
$errMsg = 'Enter username';
if ( $password == '' )
$errMsg = 'Enter password';
if ( $errMsg == '' ) {
try {
$stmt = $connect->prepare( 'SELECT id, name, username, password, access FROM users WHERE username = :username AND password = :password' );
$stmt->execute( array(
':username' => $username,
':password' => $password
) );
$data = $stmt->fetch( PDO::FETCH_ASSOC );
if ( $data == false ) {
$errMsg = "User $username not found.";
} else {
if ( $password == $data[ 'password' ] ) {
$_SESSION[ 'name' ] = $data[ 'fullname' ];
$_SESSION[ 'username' ] = $data[ 'username' ];
$_SESSION[ 'password' ] = $data[ 'password' ];
$_SESSION[ 'access' ] = $data[ 'access' ];
header( 'Location: dashboard.php' );
exit;
} else
$errMsg = 'Password not match.';
}
} catch ( PDOException $e ) {
$errMsg = $e->getMessage();
}
}
}

PHP PDO login code - repeats error, not able to login [ correct username and password is entered]

I am struggling to get the login code to run successfully. It keeps on echoing the "Username or Password incorrect.." section, though the correct username and password in entered. Am I missing something somewhere, please help.
<?php
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($_POST['username']);
$password = checkData($_POST['password']);
require ('config.php'); //database connection
global $dbselect;
$qry = 'SELECT username, password
FROM users
WHERE username = :username AND password = :password
LIMIT 1';
$statement = $dbselect->prepare($qry);
$statement->bindValue(':username', $username);
$statement->bindValue(':password', $password);
$statement->execute();
$login = $statement->fetch(PDO::FETCH_ASSOC);
if (count($login) > 0 && password_verify($password, $login['password'])) {
$_SESSION['username'] = $login['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$statement->closeCursor();
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The following worked in test ( up to the password_verify where I used a different test as I have PHP 5.3.2 and hence no password_verify ) ~ hopefully it might prove of benefit.
<?php
session_start();
/* error messages used to display to user */
$ex=array(
0 => 'One or more required POST variables are not set',
1 => 'Both username & password are required',
2 => 'Failed to prepare SQL query',
3 => 'Query failed',
4 => 'No results',
5 => 'Invalid login details'
);
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
if( isset( $_POST['Submit'], $_POST['username'], $_POST['password'] ) ) {
$username = !empty( $_POST['username'] ) ? filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) : false;
$password = !empty( $_POST['password'] ) ? filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) : false;
if( $username && $password ){
require('config.php');
global $dbselect;/* ??? */
/* use the username in the sql not password & username */
$sql='select `username`, `password`
from `users`
where `username` = :username';
$stmt=$dbselect->prepare( $sql );
/* only proceed if prepared statement succeeded */
if( $stmt ){
$stmt->bindParam( ':username', $username );
$status=$stmt->execute();
if( !$status )throw new Exception('',3);
$rows=$stmt->rowCount();
if( !$rows > 0 )throw new Exception('',4);
$result = $stmt->fetchObject();
$stmt->closeCursor();
/* password_verify is available from PHP 5.5 onwards ~ I have 5.3.2 :( */
if( $result && function_exists('password_verify') && password_verify( $password, $result->password ) ){
/* valid */
$_SESSION['username']=$username;
exit( header('Location: home.html') );
} else {
/* bogus - invalid credentials */
throw new Exception('',5);
}
} else {
/* sql prepared statement failed */
throw new Exception('',2);
}
} else {
/* either username or password was empty */
throw new Exception('',1);
}
} else {
/* one or more POST variables are not set */
throw new Exception('',0);
}
}catch( Exception $e ){
/* set a session variable to ensure error message is displayed only once */
$_SESSION['error']=$ex[ $e->getCode() ];
/* reload the login page with error code */
exit( header( 'Location: ?error=' . $e->getCode() ) );
}
}
?>
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<!-- the php/html login page -->
<form method='post'>
<input type='text' name='username' />
<input type='password' name='password' />
<input type='submit' name='Submit' value='Login' />
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['error'], $_SESSION['error'] ) ){
unset( $_SESSION['error'] );
/* display the error message */
echo "<h2 style='color:red'>{$ex[ $_GET['error'] ]}</h2>";
}
?>
</form>
</body>
</html>
/**
* You might need to save a hashed copy of the password at the point of
* user creation, so that you can password_verify the input password against the hashed
* copy returned from the DB.
* something like this :
* $hashed = password_hash($password, PASSWORD_BCRYPT);
* NOTE : I've changed you code to an extent, pls adapt.
*/
//Check login details
session_start();
//get user input from the form
if (isset($_POST['Submit'])) {
$username = checkData($username);
$password = checkData($password);
$dbname = "testo";
$servername = "localhost";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "root", "");
$parr = array($username,$password);
$qry = 'SELECT username, password, phashed
FROM users
WHERE username = ? AND password = ?
LIMIT 1';
$stmt = $conn->prepare($qry);
$Qres = $stmt->execute($parr);
$login = ($Qres) ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
if (count($login) > 0 && password_verify($password, $login[0]['phashed'])) {
$_SESSION['username'] = $login[0]['username'];
header('location:home.html');
} else {
echo "Username or Password incorrect. Please try again.";
}
$conn = null;
}
//validate data
function checkData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

How can I get the field id for a session?

I am new at php and I followed some youtube video's to build a littel project.
I have a table of users:
id
username
email
password
and I'm trying to build a private message system. I want to get the id of the user that is now logged in. But when I write my_id = $_Session[ 'id' ] I get an error : "Undefined index: id" but when I write $my_id = $_SESSION['username'] I get the username with no error and it echo's me the username. What is the difference?
That is all the code:
<?php
session_start();
$db = mysqli_connect( "localhost", "root", "", "travelersdb" );
if( #$_SESSION[ "username" ] )
{
?>
<html>
<head>
<title>Home Page</title>
</head>
<?php
include( "header.php" );
echo "<center><h1>Private Message System</h1>";
include( "message_title_bar.php" );
if( isset( $_GET[ "user" ] ) && !empty( $_GET[ "user" ] ) )
{
?>
<form method = 'post' >
<?php
if( isset( $_POST[ "message"] ) && !empty( $_POST[ "message" ] ) )
{
$user=$_GET['user'];
$my_id = $_SESSION['username']; // ------> Doesn't work when changed to 'id'
$random_number = rand();
$sql_m = "SELECT 'hash'
FROM message_group
WHERE ( user_one = '" . $my_id . "' AND user_two = '" . $user . "' )
OR ( user_one = '" . $user . "' AND user_two = '" . $my_id . "' )";
$check_con = mysqli_query( $db, $sql_m );
$rows = mysqli_num_rows( $check_con );
if( $rows == 1 )
{
echo "<p>Conversation already started!</p>";
}
else
{
echo $user . "</br>";
echo $my_id; -------> Wanted to echo the $my_id to check...
echo $random_number;
// $sql_In = "INSERT INTO message_group( user_one, user_two, hash )
// VALUES( '1111', '2222', '2222' )";
// mysqli_query( $db, $sql_In );
echo "<p>Conversation Started</p>";
}
}
?>
Enter Message : </br>
<textarea name = 'message' rows = '7' cols = '60'>
</textarea>
<br></br>
<input type='submit' value="Send Message" />
</form>
<?php
}
else
{
echo "<b>select user</b>";
$sql = "Select id,username from users";
$check = mysqli_query($db,$sql);
while ( $run_user = mysqli_fetch_array( $check ) )
{
$user = $run_user[ 'id' ];
$username = $run_user[ 'username' ];
echo "<p><a href = 'send.php?user=$user'>$username</a></p>";
}
}
?>
</html>
<?php
}
else
{
echo "You must be logged in.";
}
?>
Update: done this but still is doesn't work. doesn't identify the id. this is the login.php:
<?php
session_start();
//connect to database
$db=mysqli_connect("localhost","root","","travelersdb");
if(isset($_POST['login_btn']))
{
//$username=mysql_real_escape_string($_POST['username']);
//$password=mysql_real_escape_string($_POST['password']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password=md5($password); //Remember we hashed password before storing last time
$sql="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$sql);
if(mysqli_num_rows($result)==1)
{
$_SESSION['message']="You are now Loggged In";
$_SESSION['username']=$username;
$sql_t = "select id from users where username='$username' AND password='$password'";
$id = mysqli_query($db, $sql_t);
$_SESSION['id']=$id;
header("location:index.php");
}
else
{
$_SESSION['message']="Username and Password combiation incorrect";
}
}
?>
You may haven't set it to the session.
Use print_r($_SESSION); and check whether your index -> id is there or not.
$_SESSION index is like a variable name for your session value. If you haven't created this session/variable before, you can not retrieve its value because it is undefined

MySQLi database does not validate and return the correct result

I am making a shop database with the option to register, log in and buy items.
The steps I take are that I register as a new user. Then the details are sent to the database where I can clearly see them. After that I try to log in with the newly registered details and on the login page an error pops out saying that there has been an email and password mismatch.
I believe that there is a problem with the database not returning the correct information or maybe blocking the login tools from accessing.
The code:
Login tools.php
`
function load( $page ='login.php')
{ $url = 'http://' . $_SERVER[ 'HTTP_HOST'] . dirname( $_SERVER[ 'PHP_SELF']);
$url = rtrim( $url, '/\\');
$url .= '/' . $page;
header( "Location: $url");
exit();
}
function validate( $dbc, $email = '', $pwd = '')
{ $errors = array() ;
if ( empty( $email ) )
{ $errors[] = 'Enter your email address.' ; }
else { $e = mysqli_real_escape_string( $dbc, trim( $email ) ) ; }
if ( empty( $pwd ) )
{ $errors[] = 'Enter your password.' ; }
else { $p = mysqli_real_escape_string( $dbc, trim( $pwd ) ) ; }
if ( empty( $errors ) )
{
$q = "SELECT 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 ) ;
}
else { $errors[] = 'Email address and password not found.' ; }
}
return array( false, $errors ) ;
}
***Login Action:***
if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST')
{
require('E:\Xampp\xampp\htdocs\Michal\connect_db.php');
require('login_tools.php');
list ( $check, $data ) = validate ( $dbc, $_POST[ 'email' ], $_POST[ 'pass' ] ) ;
echo $check;
echo 'TEST';
if ( $check )
{session_start();
$_SESSION['id'] = $data[ 'id'];
$_SESSION['first_name'] = $data[ 'first_name'];
$_SESSION['last_name'] = $data['last_name'];
load ( 'home.php');
}
else { $errors = $data;}
mysqli_close( $dbc);
}
include ( 'login.php');
***Login.php:***
<?php
$page_title = 'Login' ;
include ( 'includes/header.html' ) ;
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>
Email Address: <input type="text" name="email">
Password: <input type="text" name="pass">
<p>
<input type="submit" value="Login">
</p>
</p>
<?php?>
</form>
</body>
</html>
***Register.php:***
$page_title = 'Register' ;
include ( 'includes/header.html' ) ;
if ( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
require ('E:\Xampp\xampp\htdocs\Michal\connect_db.php');
$errors = array();
if ( empty( $_POST[ 'first_name' ] ) )
{ $errors[] = 'Enter your first name.' ; }
else
{ $fn = mysqli_real_escape_string( $dbc, trim( $_POST[ 'first_name' ] ) ) ; }
if (empty( $_POST[ 'last_name' ] ) )
{ $errors[] = 'Enter your last name.' ; }
else
{ $ln = mysqli_real_escape_string( $dbc, trim( $_POST[ 'last_name' ] ) ) ; }
if ( empty( $_POST[ 'email' ] ) )
{ $errors[] = 'Enter your email address.'; }
else
{ $e = mysqli_real_escape_string( $dbc, trim( $_POST[ 'email' ] ) ) ; }
if ( !empty($_POST[ 'pass1' ] ) )
{
if ( $_POST[ 'pass1' ] != $_POST[ 'pass2' ] )
{ $errors[] = 'Passwords do not match.' ; }
else
{ $p = mysqli_real_escape_string( $dbc, trim( $_POST[ 'pass1' ] ) ) ; }
}
else { $errors[] = 'Enter your password.' ; }
if ( empty( $errors ) )
{
$q = "SELECT id FROM users WHERE email='$e'" ;
$r = mysqli_query ( $dbc, $q) ;
if ( mysqli_num_rows( $r ) != 0 )
{
$errors[] = 'Email address already registered. Login' ;
}
}
if ( empty( $errors ) )
{
$q = "INSERT INTO users (first_name, last_name, email, pass, reg_date) VALUES ('$fn', '$ln', '$e', SHA1('$p'), NOW() )";
$r = #mysqli_query ( $dbc, $q ) ;
if ($r)
{ echo '<h1>Registered!</h1><p>You are now registered.</p><p>Login</p>'; }
mysqli_close($dbc);
include ('includes/footer.html');
exit();
}
else
{
echo '<h1>Error!</h1><p id="err_msg">The following error(s) occurred:<br>' ;
foreach ( $errors as $msg )
{ echo " - $msg<br>" ; }
echo 'Please try again.</p>';
mysqli_close( $dbc );
}
}
?>
<h1>Register</h1>
<form action="register.php" method="post">
<p>First Name: <input type="text" name="first_name" size="20" value="<?php if (isset($_POST['first_name'])) echo $_POST['first_name']; ?>">
Last Name: <input type="text" name="last_name" size="20" value="<?php if (isset($_POST['last_name'])) echo $_POST['last_name']; ?>"></p>
<p>Email Address: <input type="text" name="email" size="50" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>"></p>
<p>Password: <input type="password" name="pass1" size="20" value="<?php if (isset($_POST['pass1'])) echo $_POST['pass1']; ?>" >
Confirm Password: <input type="password" name="pass2" size="20" value="<?php if (isset($_POST['pass2'])) echo $_POST['pass2']; ?>"></p>
<p><input type="submit" value="Register"></p>
</form>
<?php
include ( 'includes/footer.html' ) ;
?>
***connect_db.php:***
$dbc = #mysqli_connect ( 'localhost', 'root', 'cake', 'users' )
OR die ( mysqli_connect_error() ) ;
mysqli_set_charset( $dbc, 'utf8' ) ;
home.php:
<?php
session_start();
if(!isset($_SESSION['id']))
{
require('login_tools.php');
load();
}
$page_title = 'Home';
include('includes/header.html');
echo "<h1>Home</h1>
<P>You are now logged in_array{$_SESSION['first_name']} {$_SESSION['last_name']}
</P>";
echo'<P>
Forum |
SHOP |
Logout
</P>';
include ('includes/footer.html');
?>
'
Thank you for your help.
<?php
function load($page = 'login.php')
{
#Statements to be inserted here (steps 2-4)
$url = 'http://'.$_SERVER['localhost'].dirname($_SERVER['htdocs']);
$url = rtrim($url, '/\\');
$url .= '/'.$page;
header("Location: $url");
exit();
}
function validate($dbc, $email = ", $pwd = ")
{
#statement to be inserted here (steps 6-10)
$errors = array();
if (empty($email))
{
$errors[] = 'Enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
if(empty($pwd))
{
$errors[] = 'Enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pwd));
}
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);
}
else
{
$errors[] = 'Email address and password not found.';
}
}
return array(false, $errors);
}
?>
Can any one suggest improvements in this code.

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

Categories