I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);
Related
index.php
This is the login form
<div class="modal-body">
<form action="loginPDO.php" method="post">
<?php if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
} ?>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Username:</label>
<input type="text" name="username" id="username" placeholder="Enter Username" class="form-control">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Password:</label>
<input type="password" name="password" id="password" placeholder="Enter Password" class="form-control">
</div>
<div class="form-group">
<button type="submit" name="login" id="login" class="btn btn-primary">Login</button>
<button type="button" class="btn btn-info">Register</button>
</div>
</form>
</div>
loginPDO.php
<?php
include 'dbconnection.php';
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
header("location:index.php");
}
else
{
$query = "SELECT * FROM users WHERE username = :username AND password = :password";
$statement = $conn->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:dashboard.php");
}
else
{
$message = '<label>Wrong Data</label>';
header("location:index.php");
}
}
}
?>
Hi Guys, I want to know how to display the alert message once the user inputs incorrect credentials
For example, Imagine the user inputs wrong credentials once the user clicks the login button it automatically appears the alert message above Username.
$message just exists in file loginPDO.php and ...
$message = '<label>Wrong Data</label>';
header("location:index.php");
Is not sufficient to pass the $message variable to index.php.
As said in comments you can try
// file loginPDO.php
$message = '<label>Wrong Data</label>';
header("location:index.php?error=" . urlencode("Wrong Data"));
// file index.php
<?php
$message = isset($_GET['error']) ? $_GET['error'] : null; // get the error from the url
if(!empty($message)) {
echo '<label class="text-danger">'.$message.'</label>';
} ?>
I have a simple login page, and the idea is that if user input incorrect passowrd/login, then he or she will see error message on the same page. I have code in 3 different files - one is simple html, another has the functions, and last one runs all the logic:
<div id="content">
<div class="logo-container"><img src="images/logo2.png" alt=""></div>
<div class="container-fluid">
<!-- All login logic is in login.php file -->
<form action='/login-logic.php' method="post" class="form-1">
<p>
<label for="username" class="sr-only">Username</label>
<input type="text" class="form-control" id="username"
name="username" placeholder="What's your username?" required />
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" class="form-control" id="password"
name="password" placeholder="What's your password?" required/>
<?php
if($isValid === false) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}
?>
</p>
<p class="submit">
<button id="submit-button" type="submit" name="submit" value="submit"><i class="fa fa-arrow-right"></i></button>
</p>
</form>
</div>
// Check match of the credentials in database
function loginValidation($query) {
global $isValid;
$isValid = true;
$count = mysqli_num_rows($query);
if($count == 1) {
header('Location: pages/signup.php'); /* Redirect browser */
} else {
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
}
Thank you!
You declare a variable just before to force browser to reload the page. So the variable is no more defined in the next request.
Here is a possible way.
Instead of :
{
$isValid = false;
header('Location: index.php');
/* Redirect browser */
}
Do :
{
/* Redirect browser */
header('Location: index.php?error');
exit();
}
Then, in HTML :
if (isset($_GET['error'])) {
echo "<div id='alert-message' class='alert alert-danger'>SCRUB</div>";
}
Just edited php sliding jquery panel form and it doesn't work, actually registration works but login doesn't. I erased some code that doesn't matter in my problem...
Please ignore these error messages in this strange language.
<?php
error_reporting(0);
define('INCLUDE_CHECK',true);
require_once($_SERVER['DOCUMENT_ROOT'] . '/config.php');
session_start();
session_name('avaLogin');
session_set_cookie_params(2*7*24*60*60);
if($_SESSION['id'] && !isset($_COOKIE['avaRemember']) && !$_SESSION['rememberMe'])
{
$_SESSION = array();
session_destroy();
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
if($_POST['submit']=='Zaloguj')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'Wszystkie pola muszą być wypełnione!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
echo '';
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM ava_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('avaRemember',$_POST['rememberMe']);
}
else $err[]='Zły login i/lub hasło!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
else if($_POST['submit']=='Zarejestruj')
{
// If the Register form has been submitted
$err = array();
if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
$err[]='Twój login musi mieć pomiędzy 3 i 32 znaki!';
}
if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
$err[]='Twoje hasło zawiera niedozwolone znaki!';
}
if(!checkEmail($_POST['email']))
{
$err[]='Twój e-mail jest nieprawidłowy!';
}
if(!count($err))
{
// If there are no errors
$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
// Generate a random password
$_POST['email'] = mysql_real_escape_string($_POST['email']);
$_POST['username'] = mysql_real_escape_string($_POST['username']);
// Escape the input data
mysql_query(" INSERT INTO ava_members(usr,pass,email,regIP,dt)
VALUES(
'".$_POST['username']."',
'".md5($pass)."',
'".$_POST['email']."',
'".$_SERVER['REMOTE_ADDR']."',
NOW()
)");
if(mysql_affected_rows($avalink)==1)
{
send_mail( 'support#avatar.itterek.net',
$_POST['email'],
$SITE_NAME . ' - Twoje hasło',
'Twoje hasło to: '.$pass);
$_SESSION['msg']['reg-success']='Wysłaliśmy do Ciebie e-mail z nowym hasłem!';
}
else $err[]='Ten login jest już w użyciu!';
}
if(count($err))
{
$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}
echo('<script type="text/javascript">window.location = "' . $SITE_URL .'"</script>');
exit;
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
$script = '
<script type="text/javascript">
$(function(){
$("div#panel").show();
$("#toggle a").toggle();
});
</script>';
}
?>
<link rel="stylesheet" type="text/css" href="<?php echo $LOGIN_URL; ?>/style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="<?php echo $LOGIN_URL; ?>/login_panel/css/slide.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>
<![endif]-->
<script src="<?php echo $LOGIN_URL; ?>/login_panel/js/slide.js" type="text/javascript"></script>
<?php echo $script; ?>
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<div class="left">
<h2>REGULAMIN</h2>
<p class="grey">Rejestracja i/lub logowanie oznaczają akceptację regulaminu.
Jeśli jeszcze się z nim nie zapoznałeś to zapraszamy.</p>
<h2>DOŁĄCZ DO NAS</h2>
<p class="grey">Rejestrując się uzyskasz dostęp do szerokiej gamy polskich komiksów avatar the last airbender!</p>
</div>
<?php
if(!$_SESSION['id']):
?>
<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Logowanie</h1>
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<label class="grey" for="username">Login:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Hasło:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> Pamiętaj mnie</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Zaloguj" class="bt_login" />
</form>
</div>
<div class="left right">
<!-- Register Form -->
<form action="" method="post">
<h1>Jeszcze nie masz konta?!</h1>
<?php
if($_SESSION['msg']['reg-err'])
{
echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
unset($_SESSION['msg']['reg-err']);
}
if($_SESSION['msg']['reg-success'])
{
echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
unset($_SESSION['msg']['reg-success']);
}
?>
<label class="grey" for="username">Login:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label>Hasło zostanie Ci wysłane.</label>
<input type="submit" name="submit" value="Zarejestruj" class="bt_register" />
</form>
</div>
<?php
else:
?>
<div class="left">
<h1>Panel użytkownika</h1>
<p>Twoja subskrypcja wygasa <?php echo '???'; ?></p>
Wyloguj się
</div>
<div class="left right">
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Witaj <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Gościu';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Rozwiń panel':'Login | Reje';?></a>
<a id="close" style="display: none;" class="close" href="#">Zwiń panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div>
</body>
</html>
The problem is that here:
<li>Witaj <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Gościu';?>!</li>
user does not appear... i tried many ways to fix it and guess what?
everything works but after redirect to other page usr doesnt exists...
CHMOD 755. What's wrong with it?
As documented for session_name(), you MUST set the session name BEFORE you call session_start(). You are also changing the session cookie parameters AFTER session_start().
You cannot do this. session settings must be changed BEFORE you start the session.
I suspect that you working on the session before you've started it may be the problem.
I'm beating my head against the wall right now. I've been fiddling with this for hours, and I can't seem to figure it out.
My sessions data isn't saving when I navigate from one page to another. I've set this up in WAMP, BTW.
The cookies are being saved, and the sessions data only works when I reset it at the beginning of EVERY script. I'm not quite sure what to do here. It's probably something ridiculously stupid, but any input is greatly appreciated.
my login script:
<?php
include('../partials/_header.php');
include('includes/connectvars.php');
if(!isset($_SESSION['id'])) { //logged in?
if(isset($_POST['submit'])) { // form submitted?
if(!empty($_POST['email']) && !empty($_POST['password'])) { /* Check to make sure post isn't empty in case of JS override/disable */
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = sha1(mysqli_real_escape_string($dbc, trim($_POST['password'])));
/* query DB */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($dbc, $query) or die ("There was an error with your mySQL query:" . mysqli_error($dbc));
if(mysqli_num_rows($result)==1) { /* Check that matching row exists in users for login */
$row = mysqli_fetch_array($result);
$_SESSION['id'] = $row['id']; // set the session info
$_SESSION['type'] = $row['type'];
$_SESSION['name'] = $row['f_name'];
setcookie('id', $row['id'], time()+ (60*60*24*30));
setcookie('type', $row['type'], time()+ (60*60*24*30));
setcookie('name', $row['f_name'], time()+ (60*60*24*30));
$home_url = '/'; //redirect not working with $_SERVER variable in WAMP. keep an eye for the future
header('Location: '.$home_url);
mysqli_close($dbc);
} else { /* if no match in database ask to resubmit login info or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">Your email and/or password are incorrect. </label><br />
<label class="error">If you haven't already signed up, feel free to <a href="user_registration.php" > register</a> </label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}/* end conditional to check $rows array for username pw match */
} /* end conditional to check that form isn't blank */
else { /* If form is blank ask to resubmit or register */?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must enter your email and password if you wish to continue.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
} // end else to resubmit in case of blank form
} /* end check if form has been submitted */ else{ /* prompt for login if page visited but login form not submitted */ ?>
<script type="text/javascript" src="../js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#login_form").validate();
});
</script>
<div class="span-24 colborder">
<form id="login_form" action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
<label class="error">You must be logged in to do that!.</label><br />
<input type="text" name="email" id="email" value="" class="email required" placeholder="example#example.com"/> <br />
<input type="password" name="password" id="password" class="required" value="" /> <br />
<input type="submit" name="submit" value="Login" />
</form>
</div>
<?php
}
} /* end check if cookie isset */ else { //redirect if cookies & session is already set
$home_url = '/';
header('Location: '.$home_url);
}
?>
<?php include('partials/_footer.php'); ?>
this is my header (which includes the set session variable if cookie isset)
<?php //set session if isset cookie but not session
session_start();
if(!isset($_SESSION['id'])) {
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type'])) {
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];
}
} //end if !isset session verify
?>
and an example of the menu output depending on their session id:
<?php
if(isset($_SESSION['type']) && $_SESSION['type'] == "rnr") { //start special runner menu options
?>
<ul class="main_menu">
<li id="how_it_works" class="main_menu"><a class="main_menu" href="/user/bid_task.php">Bid on a task</a></li>
<li id="our_runners" class="main_menu"><a class="main_menu" href="/our_runners.php">Our Runners</a></li>
<li id="login" class="main_menu"><a class="main_menu" href="/user/my_account.php">My account</a></li>
<li id="register" class="main_menu"><a class="main_menu" href="/user/logout.php">Logout</a></li>
</ul>
<?php } /* end runner menu */ ?>
Thanks in advance.
The header file is included before the setcookie function is called in your login script. Based on what I see, the cookie is not set at the time you do this condition check:
if(isset($_COOKIE['id']) && isset($_COOKIE['name']) && isset($_COOKIE['type']))
And because of that it never get inside the condition statement and following lines do not get executed in the header file:
$_SESSION['id'] = $_COOKIE['id'];
$_SESSION['name'] = $_COOKIE['name'];
$_SESSION['type'] = $_COOKIE['type'];
I am trying to create a login and I am having some issues. When I log on my code prompts me for authentication (as it should if I type the wrong password) but I have the password hard coded for now. Even when I type the correct password is doing not open the link to the so I can access the page.
Note below my code:
website config files
<?php
define('WEB_ROOT' , '/mjcrawle/bank/');
define('ABSOLUTE_PATH' , '/home/mjcrawle/main/bank/');
define('URL_ROOT' , 'http://tomcat.cit.iupui.edu/mjcrawle/main/');
define('APP_ROOT' , 'http://tomcat.cit.iupui.edu/mjcrawle/main/bank/');
?>
Login process file
<?php
/*Required Fields*/
require_once('websiteconfig.inc.php');
/*FUNCTIONS*/
/*VERRIFY EMAIL ADDRESS AND PASSWORD AND MATCH IN SYSTEM*/
function validateLogin($emailaddress='', $password=''){
/*INITIALIZES VARIABLES*/
$email_key = 'betty#abc.com';
$password_key = '1234';
$auth_match = 0;
/* CHECK FOR MATCH */
if($emailaddress == $email_key && $password == $password_key){
$auth_match = 1;
}
return $auth_match;
}
/*CLEAN FORM DATA*/
function sanitize($form_var) {
$clean_data = strtolower(trim($form_var));
return $clean_data;
}
/*PAGE VARIABLES*/
$auth_status = 0;
/*DETERMINE FORM HAS BEEN SUBMITTED*/
if(array_key_exists('submit', $_POST)) {
/*SANITIZE FORM DATA*/
$emailaddress = sanitize($_POST['emailaddress']);
$password = sanitize($_POST['password']);
/*VALIDATE FORM DATA*/
$auth_status = validateLogin($emailaddress, $password);
}
?>
</div><div class="container" id="shadow">
<div>
<?php
include(ABSOLUTE_PATH . 'header.inc.php');
if($auth_status == 1){
/*AUTHENTICATION SUCCESS*/
echo '<h4>Welcome Back, Betty!</4>' . "\n\n";
echo '<ul>' . "\n";
echo "\t" . '<li>Online Banking</li>' . "\n\n";
echo '</ul>';
} elseif($auth_status == 0){
/*AUTHENTICATION FAILED*/
echo '<h4 class="error">Authentication Error!</h4>' . "\n\n";
echo '<p>Incorrect e-mail address and/or password submitted. Please try again.</p>';
}
?>
<div>
</div><!--End of main content-->
<?php
include(ABSOLUTE_PATH . 'footer.inc.php');
?>
This is my login form
<div id="login_form">
<form id="login" method="post" action="processlogin.php">
<label for="emailaddress"> E-mail Address: </label>
<input type="text" id="emailaddress" name"emailaddress" maxlength="100" tabindex="1" />
<label for="password"> Password: </label>
<input type="password" id="password" name="password" maxlength="13" tabindex="2" />
<input type="submit" id="login_submit" name="submit" value="login"/>
</form>
</div>
This is my main index page:
<?php
require_once('websiteconfig.inc.php');
?>
<div>
<h1 class="h1" align="center">
1%'er Savings <bold> & </bold> Loan </h1>
</h1>
</hr>
</div><!--End of Body--> <?php require_once('footer.inc.php'); ?> </div><!--end of header-->
This is my header
Home Login Page /_assets/stylesheets/style.css" />
/_assets/images/bkrnd_top.png">
/_assets/images/bkgrnd_tl.png" width="205"
height="61">
/_assets/images/logo.png" width="160"
height="61">
/_assets/images/background_headerarea.png">
HOME |
TBA | TBA |
TBA | TBA |
TBA
You have an error in your code. Your login form is missing a =
<input type="text" id="emailaddress" name="emailaddress" maxlength="100" tabindex="1" />
You had name"emailaddress"