The session is not passing and I want to restrict the users from viewing the login page while they are logged in for that I tried many things, but it didn't work:
My login page
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
session_start();
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>Login page</title>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="frm">
<form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
<h1> Login</h1>
<p>
<label>Username</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label>password</label>
<input type="password" id="password" name="password"/>
</p>
<p>
<input type="submit" id="btn" value="login" name="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
</p>
<p>
Not yet a member Register here
</form>
</div>
</body>
</html>
My home page
<?php
session_start();
if ($_SESSION['nID'] == false) {
header("Location: login.php");
die();
} elseif ($_SESSION['nID'] == true) {
header("Location: Home.php");
die();
} else {
echo"cant connect";
}
?>
<html>
<head>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Information</li>
<li>Logout
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</body>
</html>
The session is not passing and it doesn't prevent the user from viewing the homepage while they aren't logged in.
I have tried many different things, but nothing seems to work.
Some thoughts on this question:
1) Stop using extract(). You simply don't need it.
Warning Do not use extract() on untrusted data, like user input (i.e. $_POST, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
From the Manual.
2) As noted in another answer Your SQL query is far too vague; you're returning the first answer of a search of the whole DB rather than searching for any specific criteria.
SELECT password FROM users WHERE username=username_here LIMIT 1
And then take this row and compare with the given password:
if($password === $row['password'])
3) Your password system used on MySQL / PHP is NOT GOOD ENOUGH. Stop using md5() and employ password_hash and password_verify PHP functions. Please read how to do it properly and this comment.
4) Every time you use header("Location: ...") to redirect the user it is highly recommended you add a die or exit command immediately afterwards in order to cease the code execution on the current page. For example:
header("Location: this_page_will_never_load.php");
header("Location: this_page_will_always_load_instead.php");
5) require and include functions do not require brackets.
NOTE
Re the numerous answers here referencing session_start(); if session_start() is called after output is sent to the browser, then there will be an error notice generated. OP has not reported an error notice even with:
error_reporting(E_ALL);
ini_set('display_errors',1);
So session_start() placement in the code is not an issue in this specific situation.
However:It is best practise to put your session_start() as early as possible in your code and before such debug things as var_dump which would cause session_start not to load becase var_dump has already thrown data out to the browser.
Finally, an answer to your problem:
I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:
Your code in login.php:
if(isset($_POST['login'])){
///session stuff etc.
}
The above code on your login.php page will only execute if the page is being given POSTed data. What you have is that once someone is logged in correctly and they then return to the login.php page, they are not resubmitting the POSTed data so this code block is simply not running.
Because this code block contains all your $_SESSION references this is why it looks like $_SESSION is not running.
Instead you want to do this (simplified) in login.php:
session_start();
if(isset($_POST['login'])){
// setup session values,
// once POSTed login data is checked and authorised in the database
$_SESSION['nID'] = true;
}
elseif ($_SESSION['nID'] === true){
// is already logged in so redirect to the index page.
header("Location: index.php");
exit;
}
else {
// this fires if no POSTed data is sent and no valid
// session is found.
}
Try this condition in your home.php file:
session_start();
if (!isset($_SESSION['nID']) || empty($_SESSION['nId'])) {
header("Location: login.php");
die();
}
You try this code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
//session_start(); removed it
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
On every page, you need to add session_start() in the page heading.
First: First of all, your query is wrong. You're always checking the value with the first user in the table. You need to a query with the where clause.
SELECT * FROM users WHERE username=username_here AND password=hash_password_here
Second: Your If statement should be like the following.
<?php
session_start();
if (!isset($_SESSION['nID'])) {
header("Location: login.php");
die();
}
?>
Third: Try to use prepared statements to avoid an SQL injection.
$stmt = $link->prepare("SELECT * FROM users where username=? and password=?");
$stmt->bind_param('ss', $username, md5($password));
$stmt->execute();
$get_result = $stmt->get_result();
$row_count = $get_result->num_rows;
if ($row_count > 0) {
session_start();
$_SESSION['nID'] = true;
header('Location: home.php');
die();
}
else {
echo"Login failed";
}
4th: Don't use Md5() for passwords. Try to use password_hash() and password_verify(). Reference link.
While registrating, use password_hash() to hash the password and store it in the database and while logging in, use password_verify() to verify the password like this. Reference link.
You have to call the session_start() function in the file where you are trying to use a session variable.
You need to add session_start(); on every page to get the session variables.
Related
I was trying to code a login system in a MVC architecture, of course, handling sessions but I realized that I'm not sure if my idea is properly formulated.
I'm going to show you the code writing the pretension of this.
My view:
<?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../css/backend.css">
<script src="../js/admlog.js"></script>
<title>Access to administration panel</title>
</head>
<body>
<form method="post" action="../controller/admlog.php">
<h2><span class="entypo-login"></span> Login</h2>
<button class="submit"><span class="entypo-lock"></span></button>
<span class="entypo-user inputUserIcon"></span>
<input type="text" name="user" class="user" placeholder="username"/>
<span class="entypo-key inputPassIcon"></span>
<input type="password" name="password" class="pass"placeholder="password"/>
</form>
</body>
</html>
Nothing to say here, basic html form.
Controller of the login page:
<?php
//controller!
require "../model/backend.php";
$username = $_POST['user'];
$password = $_POST['password'];
$dbcom = new dbInteraction;
$dbcom->admlog($username, $password);
$dbcom->conclose();
?>
Very simple too, what I do here is take the values of my inputs and send them to the backend.php, where petition will be handled.
Backend function where the login is handled:
public function admlog($username, $password){
$this->username = $username;
$this->password = $password;
//$this->pdo = $pdo;
//$adm = 1;
$myquery = 'SELECT username FROM users WHERE username = :username AND password = :password'; //check admin flag
$stmt = $this->pdo->prepare($myquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
//$stmt->bindParam(':isadmin', $adm, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (count($result) > 0){
session_start();
$_SESSION['login'] = $result['username'];
header('Location: ../view/backMain.php');
}else{
session_start();
$_SESSION['login'] = "";
//header('Location: ../manage.php');
echo 'Incorrect user or password';
}
}
All the code works without problem, I mean, the select is performed correctly and user can log in the system.
The problem is the way that I handle the sessions. When user is found in the db, I coded:
session_start();
$_SESSION['login'] = $result['username'];
header('Location: ../view/backMain.php');
So it should create a new session, no? Well, the target page (backMain.php) have a restriction, restriction that check if there is a settled session or not.
<?php
if(!isset($_SESSION['login']))
{
header("Location: http://google.es");
}
?>
I have to suppose that it is, but when I try to access I see that no.
How is handled the session in this kind of architecture? For me, the code make sense but the result is obvious that not.
I'm being redirected to google.es because the condition does not find any settled session even when I set that session in the backend.
I have to be missing something.
Thanks
You are right, the problem is the way how you handle the session.
Seems, that you redirect user to another page before he gets session Cookie. Check with Chrome/FF developer console, if you receive session cookie properly.
If no, I'd recommend to make redirect on meta/js level instead of HTTP headers, it will make user receive and write cookies before being processed to another page.
I have created a login script and it works fine, however, I would like to implement sessions.. I am currently having some trouble with it because my session script is only partially executed. Below is my login script and the test page I'd like it to redirect to, IF the user is logged in.. I want it to display the test page, if not, then I want it to redirect back to the login page (or in this case, the index.php file) and ask the user to login... see code below:
loginconfig.php:
<?php
// Create a connection
include("dbconfig.php");
if (isset($_POST['submit'])) {
if (empty($_POST['username']) or empty($_POST['password'])) {
header("location:index.php?msg0=Please complete the required fields.");
}
elseif (!empty($_POST['username']) && !empty($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = mysqli_query($conn, "SELECT * FROM logininformation WHERE username = '$username' and password = '$password'") or die(mysqli_error($conn));
$login = ($sql) ? mysqli_fetch_assoc($sql) : false;
if (($login) == 0) {
header("location:index.php?msg1=Invalid username or password, please try again.");
}
elseif (($login) > 0) {
session_start();
$_SESSION['login'] = $_POST['username'];
//header("location:index.php?bid=$username&msg2=You are unable to log in at this time. Website is under construction.");
header("location:test.php?bid=$sessionwork");
}
}
}
?>
test.php:
<?php
session_start();
include("dbconfig.php");
$username = $_GET['bid'];
var_dump($_SESSION['login'];
// If user is logged in:
if(!empty($_SESSION['login'])){
echo "Welcome $username";
}
// If user is not logged in:
elseif(!isset($_SESSION['login'])){
header("location:index.php?msg4=You need to be logged in!");
}
?>
<html>
<head>
<title> user page </title>
</head>
<body>
<form name="logout" method="post" action="logout.php">
<input type="submit" name="logout" value="logout">
</form>
</body>
</html>
logout.php
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
Now if you look at the test.php file.. I have sort of told it to check if a user is logged in. But unfortunately, the script only manages to execute the script where it says if the user is not logged in.. redirect to index.php... even if the user enters the correct login credentials and actually logs in. What could be the issue?
Any help will be much appreciated.
It should be like this in test.php:
if(isset($_SESSION['login'])){
echo "Welcome $_SESSION['login']";
}
else{
header("location:index.php?msg4=You need to be logged in!");
}
The same error is repeated in loginconfig.php.
Initially, I did not have a logout.php file.. therefore I was making the mistake of not destroying my session. The change I had to make to my initial scripting was to create a logout.php file. But when I did, the problem was still present.. in order for it to work.. I made the following changes to the logout.php file.. see below:
BEFORE:
<?php
session_start();
if(!empty($_SESSION['login'])){
session_destroy();
?>
<html>
Homepage
</html>
AFTER:
<?php
session_start();
session_destroy();
header("location:index.php");
exit();
?>
Thank you for those who helped, especially #Epodax for the GREAT support.
I'm trying to create a user login system for use on a website I'm building. I have the login script and register script, but I'm having trouble with the logout and destroying the sessions.
Here's my index code. It gets the database info in config (doesn't do anything with it yet), then runs check-login to make sure the user is actually logged in. It has a logout button that routes to logout.php
<?php
include_once("config.php");
include_once("check-login.php");
session_start();
$username = $_SESSION["username"];
?>
<html>
<body>
<h1>
Hello <? echo $username ?>! We're still building, but feel free to... wait?
</h1>
<form action="logout.php">
<input class="logoutbutton" type="submit" value="Logout" />
</form>
</body>
</html>
Here is my check-login.php file. Notice that anytime I link back to the index, I'm using a $_GET to post some information into the address bar. There is no place where I simply go back to index.php
<?php
ob_start();
include_once("../myreadingplanner_config/config.php");
if(($_SESSION['username']) != null){ //If user is already logged in...
$username=$_SESSION['username'];
header("Location: index.php?Message=AlreadyLoggedIn$username");
}
else {
if(isset($_POST['username']) && strlen($_POST['username'])!=0){ //if username is valid
$username = $_POST['username'];
} else {
header('Location: login.php');
}
if(isset($_POST['password']) && strlen($_POST['password'])!=0){
$password = $_POST['password'];
} else {
header('Location: login.php');
}
$SQLString = "SELECT TOP(1) * FROM Users WHERE Username = '$username' AND Password = '$password'";
$result = sqlsrv_query($conn, $SQLString) or die ("");
if($result != null)
{
$_SESSION['username'] = $username;
header("Location: index.php?Message=YouLoggedIn$username");
} else {
header("Location: index.php?Message=UserLoginNotFound&Username=$username");
}
}
ob_flush();
?>
And finally here is my logout.php, which should (in theory) destroy the session, and head back to index.php. When it gets back to index.php, index.php will reroute to login.php using the include_once("check-login.php");
<?php
session_start();
session_destroy();
header('Location: index.php');
?>
Just looking at my logic, there SHOULD be an infinite loop in the check-login, right? Because if the user is logged in, it should reroute to index, which includes check-login, which reroutes to index, which... etc.
If you want to check out the site for yourself, please go to www.myreadingplanner.com, and use this info to login (user will be deleted eventually)
Username: StackUser
Password: password1
So functionality wise, login.php should NEVER be visible unless you have a valid session, and when it does, it should say 'Welcome $username!'. But if you hit the logout button on index, it will still keep the session open, but it will be null.
Any advice on either why logout doesn't seem to fully logout the user OR why it is logging the user out but is keeping the NULL $_SESSION around?
To remove sessions use
unset($_SESSION['SESSION_VAR'] );
session_destroy(); //closes the session and prevents session riding
For more information I'd research session riding as you should close your session as soon as you can to prevent this.
Also do not unset the entire session global array.
//don't do this
unset($_SESSION);
First, have a look at index.php file. in that file, change the code below:
include_once("config.php");
include_once("check-login.php");
session_start(); // move the session_start function and place at the top of the script
$username = $_SESSION["username"];
change it, so that it becomes like this:
session_start();
include_once("config.php");
include_once("check-login.php");
$username = $_SESSION["username"];
This problem occurs because at the file check-login.php you do not declare the function session_start();
I have tested this problem. And it works!
Successful login on my login page should direct to a homepage (which it does - I double checked to see is the variables are set and they are when a correct username/password is entered). Otherwise, the login page should be private.
LOGIN PHP (works fine)
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$error_message= "";
$user_name = "";
$user_password= "";
$_SESSION['username']="";
$_SESSION['employeeNumber']="";
if (isset($_POST['submit'])) {
$user_name = $_POST['user'];
$user_password= $_POST['pass'];
// ADD QUERY TO CHECK IF USER/PASS COMBO IS CORRECT
if(!empty($user_name) && !empty($user_password)) {
$query = "SELECT * FROM employees WHERE username='$user_name' and password='$user_password'";
$result = mysqli_query($dbc, $query)
or die ('Error querying username/password request');
if(mysqli_num_rows($result) == 1) {
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['username'];
$_SESSION['employeeNumber'] = $row['employeeNumber'];
}
header("Location: /LESSON5/3%20-%20HOMEPAGE%20:%20WELCOME.php");
exit;
} // end if rows
else {
$error_message = "You were not able to log in";
} // end else
// Direct to other webpage
} // end query
} // end isset
?>
The homepage should only be visible if the $_SESSION variables are set. If the user is not logged in (session variables not set) then the homepage should redirect to the login page. Now, I added a validation to see if variables are not set (!isset). This validation keeps the page from showing any content. When I delete this validation the HTML shows up fine. When I delete the validation and echo the variable values I get the values returned.
It's just the if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) keeping from showing any content on the page.
HOMEPAGE
<?php
session_start();
require_once("../inc_files/Lesson_5_DB_Connection.php");
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']) {
header("Location: /LESSON5/1%20-%20LOGIN.php");
}
?>
<!DOCTYPE html>
<head>
<title></title>
<meta charset="utf-8">
<link type="text/css" rel="stylesheet" href="/LESSON5/5_Signup_CSS.css">
</head>
<body>
<p><span id="logout">Logout</span></p>
<hr>
<h1>Welcome to my homepage! <br> You have successfully logged in.</h1>
<?php
mysqli_close($dbc);
?>
</body>
</html>
Is there any reason why that validation is keeping the PHP from showing the HTML(if user login is correct) or redirect the page(if user not logged in)?
Basically error is in your php if condition. One parenthesis is missing. change like this:-
if(!isset($_SESSION['username']) && !isset($_SESSION['employeeNumber']))
Note:- try to add error_reporing at the top of your all php pages so that you can get php errors if happen. check the manual of error_reporing on php site. Thanks.
If you are working on local server you can change your php.ini settings for this.
You can get how to change php.ini setting on google easily.
ini_set is function of php is for this purpose if you want to do it programmatically not with php.ini directly.
I have 3 php pages which are index.php, login.php and loginSuccess.php index.php contains only the login form and login.php contains php codes for login process.
<?php
session_start();
include './dbConnection.php';
$name = mysql_real_escape_string($_POST['userNameText']);
$password = mysql_real_escape_string($_POST['passwordText']);
$userName = stripslashes($name);
$userPassword = stripslashes($password);
$loginQuery = "SELECT * FROM users WHERE User_Name ='$userName' AND Password ='$userPassword'";
$query = mysql_query($loginQuery);
$result = mysql_num_rows($query);
if($result == 1){
$_SESSION['userName'] = $userName;
header("Location: loginSuccess.php");
}else{
header("Location: index.php");
}
?>
What i want to do is staying in the index.php with an error message if the user types wrong login information. I have a jquery function below and i want to call it in the login.php's else condition.How can i do this ? Thanks for help.
$(function(){
$('#errorDiv').fadeIn();
});
One simple way to do this would be something like this:
Change
header("Location: index.php");
to
// This is a bit rough, but, I'm guessing you're learning PHP
// so for now it'd do
header('Location: index.php?login=false');
And then in your index.php add something like
if ('false' === $_GET['login']) {
echo 'Login failed!';
}
And you'll get a beautiful message saying "Login failed!" when... a login fails.
This is in no way the 'proper' way to do this, but, it will help you learn the logic you need to know for things like this to work.
This is a loose example but hopefully you'll see the logic in it.
You could have a login form that POSTs to itself. Kind of like this:
<form method="POST action="?login">
<input type="text" name="username" />
<input type="password" name="password" />
</form>
Then at the very top of the index.php page you could include the login.php file.
<?php
if(isset($_GET['login']){
include 'login.php';
}
?>
Do the same for wherever you want the JavaScript to go.
<?php if(isset($_GET['login']){ ?>
<script type="text/javascript>
$(function(){
$('#errorDiv').fadeIn();
});
</script>
<?php } ?>
If the user logged in successfully then you just redirect to the loginSuccess.php. If not everything loads again.
You can't place your jQuery code inside login.php's else condition because it will still perform the redirect. My suggestion is that you store the error message in a session variable and then continue with the redirect back to index.php where you check if that session variable is set. If it is, you can show the error message and then "unset" that session variable.
index.php
<?php if (isset($_SESSION['error'])): ?>
<p class="error-message"><?php echo $_SESSION['error']; ?></p>
<?php unset($_SESSION['error']); ?>
<?php endif; ?>
<form>...</form>
login.php
...
else {
$_SESSION['error'] = 'the error message';
header('Location: index.php');
}