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: /");
?>
Related
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
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>";
}
I'm trying to code a login-system, but I've got a problem with the login:
As you join the webpage you get to
../?p=Login
As you press the Login-button then you should be send to
../?p=index
But the header should be
../?a=loggedin
because the standard is
Includes/index.php
The PHP-code in index:
if(isset($_GET['p'])) {
$p = htmlspecialchars($_GET['p']);
} else {
$p = "index";
}
include 'Includes/' . $p . ".php";
In the Includes/index.php is a output if a equals loggedin:
if(isset($_GET['a'])) {
if($_GET['a'] == "loggedin") {
echo('<div class="Password-true"> Du hast dich erfolgreich angemeldet.
</div>');
}
}
I think the problem might be in the login code but as I don't know where
the problem is, I inserted all of the code:
<?php
if(isset($_POST['username'], $_POST['password'])) {
$username = htmlspecialchars($_POST['username']);
$password = password_hash(htmlspecialchars($_POST['password']),
PASSWORD_DEFAULT );
$login_statement = $pdo->prepare("SELECT * FROM user_users WHERE username
LIKE :username OR email LIKE :username");
$login_statement->bindParam("username", $username);
$login_statement->execute();
$user = $login_statement->fetch();
if($user != null) {
if(isset($_SESSION)) {
session_start();
}
$_SESSION['username'] = $user['username'];
header("Location: /?a=loggedin");
} else {
echo('<div class="login-false"> Benutzername und Passwort stimmen nicht
überein. </div>');
}
}
<div class="login">
<div class="login-header">
<h1>Login</h1>
<hr size="3" />
</div>
<div class="login-content">
<form method="post" action="/?p=Login">
<h3> Benutzername / E-Mail </h3>
<input type="text" class="datainput" name="username" style="height: 30px;
padding-left: 5px;" required placeholder="Nutzername oder E-Mail" /><br>
<br>
<h3> Passwort</h3>
<input type="password" class="datainput" name="password" style="height:
30px; padding-left: 5px;" required placeholder="Passwort" /><br><br><br>
<br><br>
<input type="submit" value="Login" style="height: 30px; width: 100px;" />
</form>
</div>
<div class="login-footer">
<hr size="3" />
Fülle alle Felder aus, um dich anzumelden.
</div>
</div>
Finally I want to add, that I used a tutorial on YouTube and I use Bootstrap and jQuery.
My website is: http://mysticsouls.developed-media.de
(It isn't nice yet).
Thank you for your help!
header() will not work if the headers were already sent... aka if some code/html is displayed before this part is executed.
An alternative would be to echo some JavaScript. Since you have jquery in there I thought you might be open to an alternative ;)
<script>window.location = '/?a=loggedin'</script>
From what I can see your code has some serious security issues. You should work on a local copy first, I'd even go as far as disabling the live version... For now...
It sounds like you wanting this for a url:
/?p=index&a=loggedin
Then you can $_GET both p and a from this. Otherwise, can you clarify more?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Hi guys im having a big problem on my project i wan to have a remember me on my log in but when i try it using this code below its not working there are no error messages came out. please help me badly needed thanks in advance. here is my html code for login.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
mysql_connect("localhost", "root", "");
mysql_select_db("vrooms");
$result = mysql_query("SELECT * FROM registration where username = '$username' and password = '$password'")
or die("Failed to query database" .mysql_error());
$row = mysql_fetch_array($result);
if($username != $username){
header("location: home/homepage.php");
echo'<script>
alert("Not Allowed to Login With a Different Account!");
</script>';
$username = $_POST['username'];
}
if($row['username'] == 'admin_jake' && $row['password'] == $_POST['password']){
$_SESSION['type'] = 'admin';
}
if($row['username'] == $_POST['username'] && $row['password'] == $_POST['password'] && $_SESSION['type'] != 'admin'){
$_SESSION['type'] = 'user';
$_SESSION['username'] = $username;
header("location: home/homepage.php");
}
else if($row['username'] != $_POST['username'] && $row['password'] != $_POST['password']){
$_SESSION['message'] = "Incorrect Username or Password";
header("location: loginpage.php");
}
else if($_SESSION['type'] == 'admin' && $_SESSION['type'] != 'user'){
$_SESSION['admin'] = $username;
header("location: admin/adminpage.php");
}
if(isset($_REQUEST['remember']))
$escapedRemember = myqli_real_escape_string($conn, $_REQUEST['remember']);
$cookie_time = 60 * 60 * 24 * 30;
$cookie_time_Onset = $cookie_time + time();
if(isset($escapedRemember)){
setcookie("username", $username, $cookie_time_Onset);
setcookie("escapedPW", $password, $cookie_time_Onset);
}
else{
$cookie_time_fromOffset = time() - $cookie_time;
setcookie("username", '', $cookie_time_fromOffset);
setcookie("password", '', $cookie_time_fromOffset);
}
?>
<?php
session_start();
include_once("CORE/dbconfig.php");
if(isset($_SESSION['type'])){
if ($_SESSION['type'] == 'user') {
header("location: home/homepage.php");
}
else if ($_SESSION['type'] == 'admin') {
header("location: admin/adminpage.php");
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Car Hub - Don't dream, ride it!</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="CSS FILES/login_chstyle.css">
</head>
<body>
<br>
<?php
if(isset($_SESSION['message'])){
echo '<div class = "msg">';
echo '<p>' .$_SESSION['message']. '</p>';
unset($_SESSION['message']);
echo '</div>';
}
?>
<div class="header">
<img src="images/CarHubLogos.png" style="margin-top: 10px; height: 50px">
<!-- ___________________________________________________________________________For Log In Syntax_______________________________________________________________ -->
<div id="buttonsize"><button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Sign In</button></div>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal" style="margin-top: 50px">×</span>
<form class="modal-content animate" action="login.php" method="POST">
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" id="username" value="<?php if(isset($_COOKIE['username'])) echo $_COOKIE['username']; ?>" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" id="password" value="<?php if(isset($_COOKIE['password'])) echo $_COOKIE['password']; ?>" required>
<input type ="checkbox" id="remember" name="remember" <?php if(isset($_COOKIE['username'])){ echo"checked = 'checked'";}?> value="1">
<label>Remember Me</label>
<button class="colorgr" name="login" type="submit">Login</button>
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
</div>
<!-- ___________________________________________________________________________For Log In Syntax_______________________________________________________________ -->
<!--____________________________________________________________________________SCRIPT START ___________________________________________________________________ -->
<script>
// Get the modal for Log In
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Get the modal for sign up
var modal = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<!--____________________________________________________________________________SCRIPT END ____________________________________________________________________ -->
<!--____________________________________________________________________________Sign Up ____________________________________________________________________ -->
<div id="buttonResize">
<button onclick="document.getElementById('id02').style.display='block'" style="width:auto;">Sign Up</button>
</div>
<div id="id02" class="modal">
<span onclick="document.getElementById('id02').style.display='none'" class="close" title="Close Modal" style="margin-top: 50px">×</span>
<form name="myForm" class="modal-content animate" action="signup.php" method="post">
<div class="container">
<label><b>Last Name</b></label><br>
<input type="text" placeholder="Enter Last Name" id="customer_lname" name="customer_lname" pattern="[a-zA-Z ]+" title="Must not contain a special character and numbers. e.g. !##$%^&*0-9" required>
<br>
<label><b>First Name</b></label><br>
<input type="text" placeholder="Enter First Name" id="customer_fname" name="customer_fname" pattern="[a-zA-Z ]+" title="Must not contain a special character and numbers. e.g. !##$%^&*0-9" required>
<br>
<label><b>Contact Number </b></label><br>
<input type="tel" placeholder="Enter Contact Number" id="contact_number" name="contact_number" pattern="^\d{4}-\d{3}-\d{4}$" title="XXXX-XXX-XXXX" style = "width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;" required>
<br>
<label><b>Email</b></label><br>
<input type="email" placeholder="Enter Email" id="email_address" name="email_address" style = "width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;" required>
<br>
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" id="username" name="username" pattern="^[a-z0-9_-]{4,16}$"
title="Must contain at least 4-16 characters and must not have some special character. e.g !##$%^&*" required >
<br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" onchange="form.c_password.pattern = this.value;" required >
<br>
<label><b>Repeat Password</b></label><br>
<input type="password" placeholder="Repeat Password" id="c_password" name="c_password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Password Must Match!" required>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">Cancel</button>
<button class="colorgr" type="submit" name="submit_cus" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
<!--____________________________________________________________________________Sign Up ____________________________________________________________________ -->
</div>
<br>
<hr>
<br>
<ul>
<li>Home</li>
<li>Vehicles</li>
<li>About</li>
<li>FAQ</li>
</ul>
<div id="bodywall">
<br>
<h1 class="gety">Ride a<br>car today</h1>
<p class="stylo1">Sign up for free</p>
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="footer"><img src="images/CarHubLogos.png" style="height: 100%"></div>
</body>
</html>
<script>
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
};
} else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
} else {
ignoreHashChange = false;
}
};
}
}
</script>
First of all, you will need to keep a cookie on the client-side called hash (a randomized string), whenever a user logs in.
Along with this cookie, you must create a row in a table (sessions) within your database with the value of the hash, and the corresponding logged in user id.
For example: If user 4 logs in; it will generate a hash with the value 1234, this value will then be stored within the database table along with that users id (4).
Whenever a user visits the website, you need to check if the cookie value has been set, and if it has, check if the value matches any within the database. Assuming it finds one, grab the user id that matches with the corresponding value, and log that specific user in.
Make sure, once you've logged them in, you generate a new hash and delete the old hash from your sessions table.
Same thing goes for when the user logs out; delete the hash from the client-side and the database table, every time (for security purposes).
Hopefully, this gives you an idea of what you need to do to achieve this.
If you want a more in depth explanation on how to do this, I highly suggest reading these:
The definitive guide to form-based website authentication
What is the best way to implement “remember me” for a website?
SIDENOTE: I've noticed you're still using the deprecated mysql_* extension. Please discontinue the use of mysql_*, it is no longer secure or safe to use, and there are much better alternatives. I would suggest mysqli_* or PDO.
you have to use session_start() at the top of all your html sites, otherwise you loose reference to the session and to all its stored variables.
I want that when I press login button I get the response back in the same page e.g. if user name doesn't exist or is duplicate it should show the error message on the same page, one more thing this data goes to another page and after some database action it returns the value, I got the value in the page where I use that database query, but how to get it back to the very first page from where I actually submitted it
this is the scenario login->function selector->controller(database query page)
what I need to do is to get value from controller to login after a successful query generation here is a glimpse of code
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel"><label class="control-label" for ="loginName">Username/Email</label></div>
<div class="lbl_inpuCnt"><input type="text" class="input-xlarge" id="loginName" name="loginName" maxlength="50"/></div>
<div id="usernameError" style="font-size: 10px; color: red;"> </div>
<div class="lbel"><label class="control-label" for="loginPassword">Password</label></div>
<div class="controls">
<input type="password" class="input-xlarge" id="loginPassword" name="loginPassword" maxlength="50"/>
</div>
<div id="passwordError" style="font-size: 10px; color: red;"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
</form>
then comes the selector page
<?php
include_once 'classes/controller.php';
$controller = new controller();
switch ($_GET['type']) {
case 'signup':
$registerStatus = $controller->register($_POST);
$_POST['username'] = $registerStatus;
break;
case 'login':{
$result= $controller->login($_POST);
echo $result; //here i get the value from next page after process, i need it back to login page to show error there!
}
break;
case 'uploadSongs':
$controller->uploadSongs();
break;
case "delete":
echo "Function Called";
break;
}
?>
and this is the controller function in controller.php
public function login($request = array()) {
$login = $request['loginName'];
$password = ($request['loginPassword']);
$query = "select * from user where (user_name = '" . $login . "' OR email = '" . $login . "') AND (password = '" . $password . "')";
$user = $this->model->select($query);
if (is_array($user) && isset($user[0]['user_id'])) {
$_SESSION['uid'] = $user[0]['user_id'];
echo $_SESSION['name'] = $user[0]['first_name'];
$this->redirect("userArea.php");
} else {
echo "-1";
return $login;
}
exit;
}
Login page can submit to itself, and on a successful login, you redirect to member area. On a failed login, you simply display a message.