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>";
}
Related
[SOLVED]: This code is functional, i made a mistake by displaying an old version of my .php page into the browser, which didn't have the updated code below. I would like to echo an error 'error' produced from my php code which is meant to validate a sign in form, into the page of the sign in form, the error appears in the URL only , for example : signin.php?error= User name is incorrect. So i would like the same message to appear within the sign in form itself , i tried to use $_GET['error'] and echo'ed it within my form,
<form method="post" onsubmit=" return formSubmit() " action="signinphp.php">
<div class="userimage">
<img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture">
</div><br>
<?php if (isset($_GET['error'])){?>
<p class="error"><?php echo $_GET['error'];?></p>
<?php } ?>
<div class="error" id= "errorMsg"></div> <br>
<div class="error" id= "errorMsg1"></div>
<div class="field">
<label class="stafflabel"> Staff Name </label>
<input class="area" placeholder="staffmember or admin" onclick=" return userValidation()" onchange=" return userValidation()" id="staff" name="staffname" type="text" >
</div> <br>
<div class="error" id= "errorMsg2"></div>
<div class="field">
<label class="passlabel"> Password </label>
<input class="area" placeholder="password" onclick=" return userValidation()" onchange=" return userValidation()" id="pass" name="password" type="password" >
</div><br>
<div class="checkbox">
<input type="checkbox" class="remember-me">
<label class="remember" for="remember-me">Remember me </label>
<a class="pass-link" href="#"> Forgot password?</a>
</div><br><br><br>
<div class="field">
<input class="btn" onclick="check(this.form)" type="submit" value="Sign in">
</div> <br>
<div class="account-link">
Didn't create an account yet? Create Account
</div>
</form>
PHP
<?php
if (isset($_POST['staffname'])&& isset($_POST['password'])){
function validate($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$staffname = validate($_POST['staffname']);
$pass= validate($_POST['password']);
if (empty($staffname)){
header("Location:signin2.php?error=Staff name and password are required!");
exit();
} else if (empty($pass)){
header ("Location:signin2.php?error=Staff name and password are required!");
exit();
} else {
if ($staffname == "staffmember" && $pass== "letmein!123"){
echo "Logged in!";
header("Location: log-it-reportsbeta.php");
exit();
}
else if ($staffname == "admin" && $pass== "heretohelp!456"){
echo "Logged in!";
header("Location: sql_select_updated.php");
exit();
}
}
}
else{
header("Location: signin2.php");
exit();
}
but it did not work , i provided my form code below and the php code for the form validation, please take a look , thank you.
You may wanna use an extra condition to get an error message instead of passing the whole error string in your URL.
In your php script :
if (empty($staffname)){
header("Location:signin2.php?error=1");
exit();
} else if (empty($pass)){
header ("Location:signin2.php?error=2");
exit();
}
In your form :
if (isset($_GET['error'])) {
if ($_GET['error'] == 1) {
$message = "Staff name and password are required!";
}
else if ($_GET['error'] == 2) {
$message = "Another error message";
}
echo '<p class="error">'.$message.'</p>';
}
i have a working login form that shows up via button click, i can log in but it doesnt show the errors
button that shows login form with the function(in a seperate file):
<button type="button" class="btn btn-lg btn-success" name="button" onclick="signin()" id="signin">Login</button>
function signin()
{
jQuery('#login-form').css("display","block");
jQuery('#reg-form').css("display","none");
jQuery('#signin').css("display","none");
jQuery('#signup').css("display","block");
}
the modal with php(included to the file where the button is):
<?php
$email = ((isset($_POST['Email']))?$_POST['Email']:'');
$password = ((isset($_POST['Password']))?$_POST['Password']:'');
$errors = array();
?>
<div class="" id="login-form" style="display:none">
<img class="Lpic" src="img/loginpic.png">
<br>
<div class="fieldtext">
<h2 class="text-center">Login</h2>
</div>
<br>
<div>
<?php
if($_POST)
{
//form validation
if(empty($_POST['Email']) || empty($_POST['Password']))
{
$errors[] = 'Please enter email and password';
}
//check if email exists
$query = $db->query("SELECT * FROM users WHERE Email = '$email'");
$user = mysqli_fetch_assoc($query);
$userCount = mysqli_num_rows($query);
if($userCount < 1)
{
$errors[] = 'Unknown email, pleas verify';
}
if(password_verify($password, $user['Password']))
{
$errors[] = 'Password doesn\'t match, try again';
}
if(!empty($errors))
{
echo display_errors($errors);
}else{
//log user in
$user_id = $user['ID'];
login($user_id);
}
}
?>
</div>
<form action="Login.php" method="post">
<div class="inputfield">
<div class="form-group">
<label for="Email">Email</label>
<input type="email" name="Email" id="Email" value="<?=$email;?>">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" id="Password" value="<?=$password;?>">
</div>
</div>
<div class="form-group">
<input type="submit" value="Login" class="btn btn-success btn-block">
</div>
</form>
</div>
PS: login() is a function that logs in the user, any suggestions on how to show the errors without using alert??? TIA
Well it’s definitely not the prettiest solution, but you can instead of using the display_errors() function render the form validation messages in html whenever the $errorsarray is not empty.
Something like this:
if(!empty($errors)) {
echo ‘<div id=“errors”>’;
foreach ($error in $errors) {
echo $error . “<br>”;
}
echo ‘</div>‘;
}
Sorry that i couldn’t comletely write the code, its hard to code on the phone...
I hope you get the idea.
try setting the following at the top of your php file
ini_set('display_errors', 1);
error_reporting(E_ALL);
hope this helps.
You might also want to look at this answer
Currently working a little Sign-Up/Login system with PHP. Here is the situation:
I have this first page named "signup.php" for signing up and logging in. Once you submit your form, you are redirected to a second page called "diary.php". Once you click the submit button, a session is created respectively with your id within the "users" database. Without the diary.php, there's a logout link.
If you signed up or logged in and you are now viewing diary.php, you cannot view the signup.php page unless you press logout. Once you press logout, you are redirected to the signup.php page, but with a logout variable in the $_GET array.
<a href='signup.php?logout=1'>Logout</a>
I'm using this logout variable to check the moment there is a "logout" key exists in $_GET array, it destroys the session and redirects me back to the signup.php page.
Now here is the problem. Say I signed up for a new account, then logged out. Once I log out there's going to be a "logout" key within the GET, right? (to destroy session). If I try to sign up for another account, it actually is going to sign up me (on the database), but it automatically logs out for me since I had the logout key in my link and also because there was no session (I have in my code few lines that automatically take you back to signup.php if there is no session).
I hope that was enough to make it clear for you all. I'm going to leave the code for my two pages for you to examine. Thank you!
signup.php
session_start();
$conn = mysqli_connect("localhost","root","","diary");
$error = '';
$success = '';
if (array_key_exists("submit",$_POST)) {
if (!$_POST['email']) {
$error.= "Email field is missing.<br>";
}
if (!$_POST["password"]) {
$error .= "Password field is missing.<br>";
}
if ($error != '') {
$error = "Fill in the missing field(s):<br>".$error;
}
else if ($_POST["submit"] == "Sign up") {
$email = $_POST["email"];
$query = "SELECT * FROM users WHERE email = '$email';";
$result = mysqli_query($conn,$query);
if (mysqli_num_rows($result) != 0) {
$error .= "This account already exists!";
} else {
$email = $_POST["email"];
$password = $_POST["password"];
$query1 = "INSERT INTO users (email,password) VALUES ('$email','$password');";
mysqli_query($conn,$query1);
$success.= "Successfully signed up!";
$query = "SELECT id FROM users WHERE email = '$email';";
$row = mysqli_fetch_array(mysqli_query($conn,$query));
$id=$row["id"];
$_SESSION["id"] = $id;
header("Location: diary.php");
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$id,time() + 60*60*24*30);
}
}
} else if ($_POST["submit"] == "Login") {
$email = $_POST["email"];
$password = $_POST["password"];
$query = "SELECT * FROM users WHERE email = '$email';";
if (mysqli_num_rows(mysqli_query($conn,$query)) == 0) {
$error.= "This account does not exist, sign up for a new account!";
} else {
$query = "SELECT password FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
if ($password != $rows["password"]) {
$error.= "You have inserted the wrong password for this account. Please, try again!";
} else {
$query = "SELECT id FROM users WHERE email = '$email';";
$rows = mysqli_fetch_array(mysqli_query($conn,$query));
$_SESSION["id"] = $rows["id"];
if (!isset($_POST["signUpRemember"])) {
} else {
setcookie("id",$rows["id"],time() + 60*60*24*30);
}
header("Location :diary.php");
}
}
}
}
if (array_key_exists("logout",$_GET)) {
unset($_SESSION["id"]);
setcookie("id","",time() - 60*600);
}
if (array_key_exists("id",$_SESSION)) {
header("Location: diary.php");
}
?>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<title>Secret Diary</title>
<style>
body {
margin:0;
height: 0;
}
#error {
background-color: red;
}
body {
background-image: url("img/bg.jpg");
background-color: #cccccc;
}
#containerLogin {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
#containerSignup {
margin: auto;
width: 30%;
padding: 10px;
margin-top: 5%;
}
.switchBtt {
margin-top: 5%;
width: 70%;
}
.display-4 {
font-weight: 300;
}
</style>
</head>
<body>
<div id="error"><?php if ($error != "") { echo $error; } else { echo "<script>$( '#error' ).css('background-color', 'green');</script>"; echo $success;} ?></div>
<div id="containerLogin">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class=" text-muted "><font color="#DFD2CA">Welcome back!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">
<input type="checkbox" class="form-check-input" value="checked" name="signUpRemember">
<label class="form-check-label" for="signUpRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Login" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to sign-up panel ↹ </div>
</center>
</div>
<div id="containerSignup">
<center><h1 class="display-4 text-muted "><font color="#6D3E6C">Secret Diary</font></h1>
<br>
<h5 class="text-muted "><font color="#DFD2CA">Sign up today, for free!</font></h5>
<br>
<form method="post" name="signup">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group form-check ">s
<input type="checkbox" class="form-check-input" value="checked "name="LoginRemember">
<label class="form-check-label" for="LoginRemember">Keep me signed in</label>
</div>
<input class="btn btn-primary" type="submit" value="Sign up" name="submit">
</form>
<div class="btn btn-secondary switchBtt">Switch to login panel ↹ </div>
</center>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
</body>
<script>
$("#containerLogin").hide();
$(".switchBtt").click (function () {
$("#containerLogin").toggle();
$("#containerSignup").toggle();
});
</script>
</html>
diary.php
session_start();
if (array_key_exists("id",$_SESSION)) {
echo "<p>Logged In! <a href='signup.php?logout=1'>Logout</a></p>";
echo "<br>";
echo $_SESSION["id"]."<br>";
} else {
header("Location: signup.php");
}
?>
You generally shouldn't be using GET query strings to change state in your application for pretty much this exact reason.
GET requests are not supposed to have any side effects and browsers will try to take advantage of this to speed up page loads by either pre-requesting pages before a user clicks on them or by caching a page and not actually requesting it from the server. Either of these cases will result in unexpected behavior. Also, if someone bookmarks the page with ?logout=1 on it they'll (probably accidentally) log themselves out any time they return to the page.
It'd be better to use the POST verb for this. You can easily do with with an HTML <form> tag and a submit button:
<form action="signup.php" method="POST" id="logout_form">
<input type="hidden" name="logout" value="1" />
<input type="submit" value="Logout" />
</form>
In your PHP you can detect if someone has hit the button by doing the following:
if(isset($_POST['logout'])) {
//log user out
}
Michael's answer is a good one (and accepted!), but at the moment where I work is going through an accessibility audit, so I have that on my mind. Screen readers, people who use high contrast custom style sheets, etc. can't deal with a form button as easily as plain text.
Also I've had issues in (old) PHP clearing sessions with session_destroy, so I loop through the session variables and unset them.
Log out
And then logout.php:
<?php
session_start();
foreach($_SESSION as $sk=>$sv){
unset($_SESSION[$sk]);
}
header("location: /");
?>
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);
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'];