I'm was doing this tutorialHow to create a login system in PHP
I'm trying to use an IF statement to check if to set the session id. The current allows a user to log in and echos the current session id. When I purposely enter a wrong password, the code should echo a message, but it doesn't do anything. In addition, I am unable to use the logout button to kill the session.
Here is my login page
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
Here is my logout page.
<?php
session_start();
session_destroy();
header("Location: fakelogin.php");
?>
here is the main page that contains login, signup and logout buttons.
<?php
session_start();
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Look ma, no hands!</title>
</head>
<body>
<form action="login.php" method="POST">
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="login">LOGIN</button>
</form>
<?php
echo("testing");
if(isset($_SESSION['id'])){
echo($_SESSION['id']);
} else {
echo("You are not logged in");
}
?>
<br><br><br>
<form action="signup.php" method="POST">
<input type="text" name="first" placeholder="Enter first name"><br>
<input type="text" name="last" placeholder="Enter last name"><br>
<input type="text" name="uid" placeholder="Enter username"><br>
<input type="password" name="pwd" placeholder="Enter password"><br>
<button type="submit" id="sbt">SIGN UP HERE YO!</button>
</form>
<br><br><br>
<form>
<button action="logout.php">LOG OUT</button>
</form>
</body>
</html>
Based on the code you have provided, you will always return to the login page.
When logged in, the string below login button will say testing followed by your user account id.
Otherwise, it will show testingYou are not logged in.
You cannot add a message on login.php and expect it to appear on fakelogin.php auto-magically.
There are a lot of ways to share information between pages and the session variable is one of it.
By using the method below, you can set the session variable id as "Your username or Password is wrong" and since fakelogin.php will print it out if there's a value, this should show the error message.
login.php
<?php
session_start();
//include 'dbh.php';
//probably do not need this can write connection in this file too
$conn = new PDO('mysql:host=localhost;dbname=testtable', 'root', '');
$conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
if(!$conn){
die("Connection is fubar yo!!! ");
}
$uid = $_REQUEST['uid'];
$pwd = $_REQUEST['pwd'];
$sql = "SELECT * from user WHERE uid='$uid' AND pwd='$pwd'";
$result = $conn->prepare($sql);
$result->execute();
if(!$row = $result->fetch(PDO::FETCH_ASSOC)){
echo("Your username or Password is wrong");
$_SESSION['id'] = "Your username or Password is wrong";
} else {
echo("hey man..it works");
$_SESSION['id'] = $row['id'];
}
header("Location: fakelogin.php");
?>
So when you attempt to login with wrong details, you will see testingYour username or Password is wrong.
For problem with your logout button, there's a problem with your HTML. action attribute should be in the form tag and not the button tag like so.
<form action="logout.php">
<button>LOG OUT</button>
</form>
For login im using a session_start(), for desktop its works fine, but on mobile, it doesnt work. When I make a session_id() with variable, for example, session_id('login') its works on mobile, but break other sessions on other computers. But when session_id() is generated automatically, it doesn't work on mobile. What should I do?
My session_start code on index.php
session_start();
if (isset($_SESSION['username'])){
session_id();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if (password_verify($password, $row[0])){$passwordOK = true;}
if($usernameOK == true && $passwordOK == true){
$_SESSION['username'] = $username;
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
Not really sure what your code does, because I dont see anything regarding setting the username or anything of that sort. What your code does is, it starts the session and checks if username variable in session is set, and if YES, it calls session_id.
Can you use this to check if the session is created properly?
session_start();
if (session_status() !== PHP_SESSION_NONE)
{
echo session_id();
}
Starts a session and shows you the session ID if the session_status is not PHP_SESSION_NONE
You don't need to do a session_id() to start a session, session_start() is enough.
I've tested the following on Safari on iPhone 6 (just add the db query part back if you want):
testa.php
<?php
//require('config.php');
session_start();
echo "Session ID: ".session_id()." <br>\n";
$usernameOK = false;
$passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$usernameOK = true;
$passwordOK = true;
if ($usernameOK == true && $passwordOK == true) {
$_SESSION['username'] = $username;
} else {
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])) {
header("Location: ../");
exit;
} else {
?>
<form class="login-form" method="POST">
<?php if (isset($error_message)) { ?>
<div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
testb.php
<?php
session_start();
echo "Session ID: ".session_id()." <br>\n";
echo "Data stored in session: {$_SESSION['username']}<br>\n";
Clear data/cookies on your mobile browser (or just go into incognito mode). This will make sure you "start from scratch".
Open testa.php on your mobile browser. Take note of the session id shown. Enter your login details and tap Submit. The next page may show blank.
Open testb.php. Again, take note of the session id shown. It should be equal to the session id shown in test1.php. If they are different then it is possible your mobile browser is configured not to accept cookies.
I've personally tested this on Safari on iPhone 6 and I was able to get the username data from session.
PS. A friendly reminder: don't forget to escape the data you use in queries (i.e. $username and $password). Use mysqli_real_escape_string, or use prepared statements. For security.
Maybe you are experiencing some conflict issues:
My session_start code
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
Whole code for login.php file
<?php
require('config.php');
$usernameOK = false; $passwordOK = false;
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT username FROM `members` WHERE username='$username'";
$userTestResult = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($userTestResult);
if($usernameTEST == 1){$usernameOK = true;}
$PasswordQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection,$PasswordQuery);
$row = mysqli_fetch_row($result);
if($usernameOK == true && password_verify($password, $row[0])){
if (isset($_SESSION)){
$_SESSION['username'] = $username;
} else{
session_start();
$_SESSION['username'] = $username;
}
}else{
$error_message = "Incorrect login data";
}
}
if (isset($_SESSION['username'])){
header("Location: ../");
exit;
}else{?>
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
<?php } ?>
In the index.php on the first line I have -> REMOVE THAT, PUT FIRST ROUTINE OF SESSION CHECKING
if (!isset($_SESSION)){
session_start();
}
EDIT: I noted that you're using header function to redirect to the index page. It's important avoid such redirects unless you're sending user out of your system, because some environments doesn't work well with them. I suggest to change your routine to user POST/GET http routines instead:
Inside validateSession.php
outside validateSession, NOTHING about sessions rules, concentrate everything there
index.php/head.php/some code that always starting in every page start only that:
<?php
include_once('validateSessions.php');
?>
Your form:
<form class="login-form" action="index.php" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
EDIT: I reviewed your routine, pay attention on validateSessions.php, I was forgetting to load session_start() in every routine that called the file. Put validateSessions inside your include directory.
UPDATE: Even my code helping the OP, the main problem was the SESSION configuration into php.ini file with session.save_path, causing issues about session routines. The php.ini fix solved the problem, the code I expect that helped OP to think about some routines towards Session stuff.
Probably your session is not set. Depending on the PHP version you use, check your session.
For versions of PHP >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
Cookies definitely work on mobile browsers.
I have simplified the code and the session is started when all checks are passed.
<?php
require('config.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$UserQuery = "SELECT password FROM `members` WHERE username='$username'";
$result = mysqli_query($connection, $UserQuery);
$usernameTEST = mysqli_num_rows($result);
if($usernameTEST == 1){
$row = mysqli_fetch_row($result);
if(password_verify($password, $row[0])) {
session_start();
$_SESSION['username'] = $username;
header("Location: ../");
exit();
}
}
$error_message = "Incorrect login data";
}
<form class="login-form" method="POST">
<?php if(isset($error_message)){ ?><div class="mini-mes error"> <?php echo $error_message; ?> </div><?php } ?>
<span class="placeholder">username</span>
<input type="text" name="username" placeholder="username" required>
<span class="placeholder">password</span>
<input type="password" name="password" id="inputPassword" placeholder="password" required>
<button type="submit">Login</button>
<a class="form-link" href="register.php">Register</a>
</form>
Simplified the code to make it easier to understand.Ignoring checks for username and password etc. You're basically trying to set a session variable. That happens in login.php. Code for that is.
<?php
$username = "Umesh";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
?>
In index.php you're trying to check the session status. The code is below.
if (isset($_SESSION['username'])){
session_id();
} else if (!isset($_SESSION)){
session_start();
}
print_r($_SESSION);
The above works for me on every browser and device. I even tested chrome on iphone. It seems to work fine. Please check this and see if it works. If not, we will have to check your webserver to see, what the issue is, with session objects on that system.
I verified that print_r ($_SESSION) was same in both cases.
Why you use session_id(). session I am always use this login system. I have no problem Desktop or Mobile session.
PHP code
<?php
session_start();
include 'connect.php';
if(isset($_POST['submit']))
{
$username = htmlspecialchars($_POST["uname"], ENT_QUOTES, "ISO-8859-1");
$username = stripslashes($username);
$password = htmlspecialchars($_POST["pass"], ENT_QUOTES, "ISO-8859-1");
$password = stripslashes($password);
$sql="SELECT * FROM member WHERE username= '$username' AND password='$password' AND status='1' ";
$result=mysql_db_query($dbname,$sql);
$row=mysql_fetch_row($result);
$num=mysql_num_rows($result);
$msg= "<h3 style='padding:0px;margin:0px;font-size:16px;background:#fff;padding:8px;'><font color='red'><center>Incorrect login data</center></font></h3>";
if($num>0)
{
$_SESSION['id'] =$row[0];
$_SESSION['fullName'] =$row[1];
$_SESSION['username'] =$row[2];
$_SESSION['password'] =$row[3];
$_SESSION['email'] =$row[4];
$_SESSION['userType'] =$row[5];
$_SESSION['status'] =$row[6];
header('location:index.php');
}
}
?>
My HTML Form
<form method="post">
<p><?php if (isset($_POST['submit'])) { echo $msg; } ?> </p>
<div>
<input type="text" name="uname" class="form-control" placeholder="Username..." required="" />
</div>
<div>
<input type="password" name="pass" class="form-control" placeholder="Password..." required="" />
<p align="right">Forgot it?</a></p>
</div>
<div>
<button class="btn btn-success submit" type="submit" name="submit"> Login <i class="fa fa-sign-in"></i></button>
</div>
</form>
Remove session_start(); in index.php
and Add this in your config.php
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
Going by your last comment I guess it is due to the query string you are using. Basically using password as a column name sometimes breaks the query as password is also a mysql keyword.
Also, regarding your session you can refer to session_id() vs session_regenerate_id() for further details regarding the functions. Session_id('login') basically sets the session id to login which works on your mobile device as this creates the session with the specific static id. However, you can try using session_regenerate_id(true) to see if it helps.
Also i tried executing the code by putting static value as username as follows
login.php
<?php
$username = "deadlock";
if (isset($_SESSION))
{
$_SESSION['username'] = $username;
}
else
{
session_start();
$_SESSION['username'] = $username;
}
print_r($_SESSION);
index.php
<?php
if (isset($_SESSION['username'])){
session_regenerate_id(true);
} else if (!isset($_SESSION)){
session_start();
}
print_r(session_id());
I started using index.php directly using the phone which printed the output as array() with no values.turned out that the Login.php file is not executed.after I explicitly executed Login.php the index.php printed the session array. Can you make sure that the login php file is properly executed.
Regards
Check that session_start() is placed before any browser output. I have found that Chrome on Desktop can be a lot more forgiving then other browsers as well as Mobile Chrome
This problem is generated with Chrome "Lite Mode" to reduce data load throw the Phone. If you use secret navigation so the lite mode is automatically disable an page work correctly. You have to disable "Lite Mode" on Chrome.
This is the final solution.
My problem was on server-side the session.save_path not definied to my server. Thanks a lot to all, who helped me :)
I am currently organising my files into appropriate folders and a problem has arisen. Before changing the code to organise the files everything worked. Now whenever I try to log in, instead of redirecting to 'Staff/staff.php', it redirects to 'Staff/index.php'.
The code is as follow:
<?php
session_start();
include("connectdb.php");
//if the form has been submitted
if (isset($_POST['submitted'])){
//get the information out of get or post depending on your form
$username = $_POST['username'];
$password = $_POST['password'];
global $db;
//sanitise the inputs!
$safe_username = $db->quote($username);
//run a query to get the user associated with that username
$query = "select * from user where username = $safe_username";
$result = $db->query($query);
$firstrow = $result->fetch(); //get the first row
if (!empty($firstrow)) {
//check the passwords, if correct add the session info and redirect
$hashed_password = md5($password);
if ($firstrow['password'] == $hashed_password){
$_SESSION['id'] = $firstrow['userID'];
$_SESSION['username'] = $firstrow['username'];
$_SESSION['fname'] = $firstrow['first_name'];
$_SESSION['lname'] = $firstrow['last_name'];
$_SESSION['staff'] = $firstrow['staff'];
if($firstrow['staff'] == 1) {
header("Location:Staff/staff.php");
exit();
} else {
//echo "Success!";
header("Location:Customer/customer.php");
exit();
}
} else {
echo "<h1>Error logging in, password does not match</h1>";
}
} else {
//else display an error
echo "<h1>Error logging in, Username not found</h1>";
}
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="CSS/theme.css">
</head>
<body>
<h1 class="register-title">Aston Animal Sanctuary</h1>
<div class="register">
<!--<form method="link" action="staff.php">
<input type="submit" value="Staff Login">
</form>-->
<form action="index.php" method="post">
<input type="text" class="register-input" name="username" placeholder="Username">
<input type="password" class="register-input" name="password" placeholder="Password">
<input type="submit" value="Login" class="register-button">
<input type="hidden" name="submitted" value="TRUE" />
</form>
<form method="link" action="register.php">
<input class="register-button" type="submit" name="register" value="Register">
</form>
<div>
<!--Test-->
</body>
</html>
<?php include('View/footer.html'); ?>
Is the header the problem?
EDIT
The same thing happens with my logout file. It redirects to 'Staff/logout.php' instead of '../logout.php'. It worked before I started organising the files.
The code for logout.php:
<?php
session_start(); //get the previous session info
session_destroy(); //destroy it
header("Location: ../index.php"); //redirect back to the start
?>
Have you tried:
header("Location: ./staff/staff.php");
and:
header("Location: ./customer/customer.php");
I have a form which allows users to enter their data. It then checks these data against a database to see if the user exists. If so, it logs them into a certain page.
I would then like to allow them to log out (such that they no longer have access to that certain page). To this end, I created a "logout.php" document in which I try to clear the login details.
However, having done this, if I try load the login page, it takes me back to the logged in page.
Here is my code (login.php - creating the form and logging the user in):
<?php //Start the Session
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password']))
{
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking if the values exist in the database
$checkLogin = $connection->query("SELECT * FROM users
where (username='$username' && password='$password')");
$numRows = $checkLogin->fetchColumn();
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($numRows >= 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo '<script>window.alert("Invalid Login Credentials")</script>';
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "
";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
echo $username;
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<head>
<title>CodingCyber - Simple Login Script</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="login.php" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="register.php">Signup</a>
<input class="btn register" type="submit" name="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
The "require('connect.php')"; just connects to my MySQL database. This code all seems to run fine, in that it does log users in, once validated. I've just included it for completeness w.r.t. the problem.
As you can see, once logged in it displays text saying "Member's area", with a logout hyperlink.
Here is my logout.php code (which I would like to remove access to the member's area, and take user back to the login page):
<?php
session_start();
$username = '';
$password = '';
$confirmPassword = '';
$email = '';
echo $username;
unset($_POST['username']);
unset($password);
?>
This second bit of code is where, to be honest, I'm really not sure what I'm meant to do to remove the access privileges.
I've looked at a few other questions, but can't seem to find the solution.
Any help would be awesome! Please let me know if there is a similar thread or if you need more information.
Thanks!
Try this:
unset($_SESSION['username']);
It will remove the username variable from the session
You need to destroy the session variables:
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
$url = 'http://example.com';
header( "Location: $url" );
exit();
So this is the code for page index.php: the $_SESSION["username"] variable seems to be not setted and I dunno why becuase in the login page I am using the isset control and the login is successful if I'm entering the right values;it is not if I am entering wrong username and password. I know I should "code" the password with md5 but right now that is not my problem :(
As you can see I'm redirecting to the index page after the login. From the index page I'm redirecting to the "home.php" page if the user already logged in. The problem is that after been doing the login,it keeps showing the login form and it is not redirecting me to home.php..
<?php session_start();
require_once "dbConn.php"; dbconnect();
if(isset($_SESSION["username"])){
echo $_SESSION["username"]; // TEST it never enters THERE!!!
echo'<p>Trasferimento alla home page</p>';
header("Refresh: 2; URL = home.php");
}
else{
echo'<div id=\"container\">';
echo'
<div id=\"content\">
<h2> You need to login :</h2>
<br/>
<form id="form1" name="form1" method="post" action="login.php">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<input type="submit" name="accedi" id="accedi" value="Accedi" />
</form>
<br/>
</div>';
include 'Footer.php';
echo'</div>';
}?>
And this is the login.php page:
<?php
require_once "dbConn.php"; dbconnect();
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=mysql_real_escape_string($_POST['username']);
$pwd = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM user WHERE username='$username' AND password ='$pwd';");
if(mysql_num_rows($query) == 1){
$sessione =mysql_fetch_array($query);
$_SESSION["username"] = $sessione["username"];
echo $_SESSION["username"]; //TEST - it prints what I want: my username
$_SESSION["logged"] = true;
echo'Login effettuato con successo!';
header("Refresh: 2; URL = index.php");
}
else if((mysql_num_rows($query) == 0)){
echo'Utente non registrato o password errata';
header("Refresh: 2; URL = index.php");
}
}
?>
Thx all ;)
You forgot to call session_start() on your login page
<?php
require_once "dbConn.php"; dbconnect();
should be
<?php
session_start()
require_once "dbConn.php"; dbconnect();