Can't get login success to view - php

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

Related

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.

php header location redirect blank page

I have a problem with header location redirect me to a blank page without making me see the code and the browser does not report any error. I work locally with exampp
class UserController
{
public $username = '';
private $logged = false;
private $usermodel = '';
public function __construct()
{ session_start();
$this->usermodel = new UserModel();
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_GET['action'])&& $_GET['action']== 'login' ){
$username = (isset($_POST['username']))? $_POST['username'] :false ;
$password = (isset($_POST['password']))? $_POST['password'] :false ;
if ($username !=false && $password !=false && $this->usermodel->checkLogin($username, $password)){
$this->username =$username ;
$this->logged = true ;
$_SESSION['username']= $username ;
$_SESSION['logged']= true ;
$_SESSION[ 'message' ] = 'Login effettuato correttamente';
}else{
$_SESSION[ 'message' ] = 'Errore con il login; riprovare!';
}
}
elseif (isset($_GET['action'])&& $_GET['action']== 'logout'){
unset($_SESSION['username']);
unset($_SESSION['logged']);
$_SESSION[ 'message' ] = 'Logout effettuato correttamente';
}
elseif (isset($_SESSION['username'])&& isset($_SESSION['logged'])){
$this->username = $_SESSION['username'] ;
$this->logged = true ;
}
elseif(($_SERVER['REQUEST_METHOD']=='POST' && isset($_GET['action'])&& $_GET['action']== 'registra' )){
$username = (isset($_POST['username']))? $_POST['username'] :false ;
$password = (isset($_POST['password']))? $_POST['password'] :false ;
$repassword = (isset($_POST['repassword']))? $_POST['repassword'] :false ;
$nome_reale = (isset($_POST['nome_reale']))? $_POST['nome_reale'] :false ;
$email = (isset($_POST['email']))? $_POST['email'] :false ;
if ($username !=false && $password !=false && $repassword !=false && $nome_reale && $email !=false
&& $this->usermodel->Registration($username,$password,$repassword,$nome_reale,$email) )
{
$this->username =$username ;
$this->logged = true ;
$_SESSION['username']= $username ;
$_SESSION['logged']= true ;
$_SESSION[ 'message' ] = "registrazione effettuato correttamente benvenuto $username";
}
}
$this->redirectToProperArea();
}
public function logged(){
return $this->logged ;
}
public function redirectToProperArea(){
$script_file = basename( $_SERVER[ 'SCRIPT_NAME' ] );
if ( $this->logged() && $script_file == 'login.php' ) {
ob_end_clean();
header('Location: ../index.php' );
exit;
}
elseif ( !$this->Logged() && ( $script_file == 'index.php' && isset( $_GET[ 'action' ] ) && $_GET[ 'action' ] != 'index' && $_GET[ 'action' ] != 'detail' && $_GET[ 'action' ] != 'logout' ) ) {
ob_end_clean();
header('Location: ../login.php');
exit;
}
elseif ( $this->logged() && $script_file == 'registra.php' ) {
ob_end_clean();
header('Location: views/benvenuto.php');
exit;
}
}
}
I Solved using the Function
`if (!headers_sent()) {
header('Location:views/benvenuto.php');
exit;
} `
Now I have another problem in benvenuto.php page I have an include ( ' messagge.php ' ) ; which is always in the views directory which is the same as benvenuto.php I find myself always with me does not load the blank page includes
Thanks for your help
Have you tried to replace :
header('Location:...');
to
echo '<script>document.location="..."</script>';

Error with PhP Script login_tools

I'm coding a basic PhP login script right now to develop later on, I've got as far as the Login_tools.php file but when I login in with the wrong details (to check login_tools is working) however I get this error:
"PHP Syntax Check: Parse error: syntax error, unexpected '$un' (T_VARIABLE) in your code on line 27
$q = "SELECT user_id, username FROM users WHERE username = '$un' AND pass = SHA1('$p')" ;"
<?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, $username =", $pwd=")
{
$errors = array();
if( empty($username))
{ $errors[] = "Enter your username."; }
else
{$un = mysqli_real_escape_string( $dbc, trim( $username));}
if( empty( $pwd))
{ $errors[]= "Enter your password.";}
else
{$p = mysqli_real_escape_string($dbc, trim($pwd)); }
if(empty( $errors))
{
$q = "SELECT user_id, username FROM users WHERE username = '$un' 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[] = 'Username and/or Passsword not found.';}
}
return array ( false, $errors) ; }
?>
Any help as to why I am getting this error would be much appreciated...
The error is in this line:
url = rtrim( $url, '\');
backslash is an escape char.
Change it to
url = rtrim( $url, '\\');
and the error goes away.
Try this one:
<?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, $username ="", $pwd="")
{
$errors = array();
if( empty($username))
{ $errors[] = "Enter your username."; }
else
{$un = mysqli_real_escape_string( $dbc, trim( $username));}
if( empty( $pwd))
{ $errors[]= "Enter your password.";}
else
{$p = mysqli_real_escape_string($dbc, trim($pwd)); }
if(empty( $errors))
{
$q = "SELECT user_id, username FROM users WHERE username = '$un' 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[] = 'Username and/or Passsword not found.';}
}
return array ( false, $errors) ; }
I hope this helps.

Action script for login form not working

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...

Why doesn't my session work?

hey guys i dunno why i couldnt echo $_SESSION['name'] on index.php
says
Undefined index: name in C:\xampp\htdocs\STT\index.php on line 52
You are logged as
PHP code:
$username = (isset($_POST['username'])) ? trim($_POST['username']) : '' ;
$password = (isset($_POST['password'])) ? trim($_POST['password']) : '' ;
if (isset($_POST['submit']) && ($_POST['submit'] = 'Login')) {
$query='SELECT * FROM user_info WHERE username = "'. $username .'" AND password = PASSWORD("'. $password .'") ';
$result = mysql_query($query) or die(mysql_error()) ;
$count = mysql_num_rows($result) ;
if ( $count == 1 ) {
$_SESSION['logged'] = 1 ;
$_SESSION['name'] = $_POST['username'] ;
echo 'successfully logged.' ;
header ('Refresh : 5 ; URL = index.php') ;
}
else {
echo 'Invalid username or password' ;
$_SESSION['logged'] = 0 ;
}
}
and index.php
<?php
if ( $_SESSION['logged'] = 1) {
echo 'You are logged as' . $_SESSION['name'] ;
}
else {
echo 'WTF';
}
?>
I don't see session_start() anywhere.
Start new or resume existing session
Be sure to add it before any output to the page (includes whitespace).
Did you have
session_start();
in every page you use session?

Categories