Not sure if using isset correctly - php

I am building up a website that must not show login option when the user is already logged in, i.e. session is active. I have tried working with this but its not returning the desired output. Please help. Thanks.
<?php
if(!isset($_SESSION)) {echo "<li><a href='Employee.php'>Login</a></li>";}
?>
edit:
I am adding the part where I check login details from database and start session.
$query = "SELECT Cust_FName from customer where Cust_ID='$name' and Password='$pass'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)!= false)
{
$row = mysqli_fetch_row($result);
echo row[0];
if(mysqli_num_rows($result) > 0)
{
echo "Logged in!";
session_start();
$_SESSION['userName'] = $row[0];
header("Location: index.php");
}
}

If you want to check if the session is started, you can use
if(session_status() != PHP_SESSION_ACTIVE) {
echo "<li><a href='Employee.php'>Login</a></li>";
}
The problem is that the session als also there if the user isn't logged in. You have to check if e.g. $_SESSION['user_id'] is set:
if(!isset($_SESSION['user_id']) {
echo "<li><a href='Employee.php'>Login</a></li>";
}
In my example $_SESSION['user_id'] will be filled when the user login was successful.

Problem
From your comment:
The login button should only show up when the user has not logged in, and once he does, it should disappear.
Solution
// This would be your login.php page
<?php
session_start();
// process your HTML form, like this
if(isset($_POST['login'])){
// Remember: always validate your form inputs
$name = $_POST['name'];
$pass = $_POST['pass'];
$query = "SELECT Cust_FName from customer where Cust_ID='$name' and Password='$pass'";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result)!= false){
$row = mysqli_fetch_row($result);
//echo row[0];
if(mysqli_num_rows($result) > 0){
//echo "Logged in!";
$_SESSION['userName'] = $row[0];
header("Location: index.php");
exit(); // exit() is necessary, otherwise the script execution is not terminated. Setting header alone is not enough to redirect.
}
}
}
if(isset($_SESSION['userName'])){
// user is already logged in
// redirect the user to a different page
// header("Location: index.php");
// exit();
}else{
// user is not logged in
// display login option
?>
<!--Your HTML form for login-->
<form action="login.php" method="POST">
<input type="text" name="name" value="" /><br />
<input type="text" name="pass" value="" /><br />
<input type="submit" name="login" value="Login" />
</form>
<?php
}
?>
Edited:
Session is a file that resides in our server and in that file we can store any amount of information. We generally deploy a session cookie on the client's browser.
Before we output any HTML or white space, we need to start our session.
When we do like this,
<?php
session_start();
?>
It will say, go to the browser, get the session id and open the appropriate file and if it didn't find any session id, it will start a new session. User can only see session id, nothing else.
Tip: Remember to clean up sessions from time to time.

Put in the login page
<?php
session_start();
// Store Session Data
$_SESSION['login_user']= $username; // Initializing Session
?>
when you have to check use
<?php
session_start();
// Store Session Data
if(isset($_SESSION['login_user'])){
//do things
}
?>
and on logout
<?php
session_destroy();
?>

Related

Login not retaining user info

I have created a basic user login function for my website, but it doesn't seem to be retaining the fact that the user is already logged in.
I have tried creating a function called 'logged_in' in my 'login_tools' file to check if the user is already logged in, and have tried to call this in the 'user_home' file but it isn't recognising it. I can't be sure then that it is actually working. Am I calling this the right way or in the right place? Or could it be a problem with the actual function itself?
I need to ensure that users can remain logged in until they log out manually themselves, as this underpins the next phase of my site, in which they can access database info that is specific to them.
Am posting those two files below, along with others for context.
Any advice appreciated on what I may be doing wrong.
login.php
<!DOCTYPE HTML>
<?php
include("includes/db.php");
include("includes/head.php");
include("includes/search_box.php");
include("includes/left_sidebar.php");
?>
<html>
<body>
<h1>Login form</h1>
<form action="login_process.php" method="POST">
<p>
Email address: <input type="text" name="email"></p>
<p>
Password: <input type="password" name="password"></p>
<p>
<input type="submit" value="Login"></p>
</form>
</body>
</html>
<?php
if (isset($errors) && !empty($errors)){
echo'<h1>Error!</h1>
<p id="err_msg">There was a problem!<br>';
foreach($errors as $msg){
echo "- $msg<br>";
}
echo 'Please try again or Register your profile</p>';
}//if
?>
login_tools.php
<?php
function load_page($load_page = 'login.php'){
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url = rtrim($url,'/\\');
$url.='/'.$load_page;
header("Location:$url");
exit();
}//load_page
function logged_in(){
return (isset($_SESSION['user_id'])) ? true : false;
}
function validate_user($con, $user_email='', $user_password=''){
$errors=array();
if (empty($user_email)){
$errors[]='Please enter your email address!';}//if
else
{$email = mysqli_real_escape_string($con, trim($user_email));}//else
if (empty($user_password)){
$errors[]='Please enter your password!';}//if
else
{$password = mysqli_real_escape_string($con, trim($user_password));}//else
if(empty($errors)){
$query_users = "select user_id, fName, sName from users where user_email='$email' and user_password=SHA1('$password')";
$run_query_users=mysqli_query($con, $query_users);
if (mysqli_num_rows($run_query_users) == 1){
$row = mysqli_fetch_array($run_query_users, MYSQLI_ASSOC);
return array(true, $row);
}//if
else { $errors[] = 'Email and password have not been found';
}//else
}//if
return array(false, $errors);
}
//validate_user
?>
login_process.php
<?php
//Check login form has been submitted correctly
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
require("includes/db.php"); //Open db connection
require("login_tools.php"); //Access login tools
require("functions/functions.php");//
//Verify if login has been successful and fetch user details
list($verify, $details) = validate_user($db, $_POST['email'], $_POST['password']);
//Set session data for user details & load user homepage
if ($verify){
session_start();
$_SESSION['user_id'] = $details['user_id'];
$_SESSION['fName'] = $details['fName'];
$_SESSION['sName'] = $details['sName'];
load_page('user_home.php');
}//if
else {$errors = $details;}
//Close db connection
mysqli_close($db);
}//if
include ('login.php');
?>
user_home.php
<!DOCTYPE HTML>
<?php
include("includes/db.php");
include("includes/head.php");
include("includes/search_box.php");
include("includes/left_sidebar.php");
?>
<?php
session_start();
//Check if user is logged in already or proceed with logging them in
if (logged_in === true) {
echo 'You are already logged in!Logout';
}
else {
if (!isset($_SESSION['user_id'])){
require('login_tools.php');
load_page();
}//if
//Confirm user is logged on
echo"<h1>PROFILE PAGE</h1>
<p>You have successfully logged in, user number {$_SESSION['user_id']} {$_SESSION['fName']} {$_SESSION['sName']}</p>";
echo '<p>
Your itinerary
Your details
Logout
</p>';
}//else
?>
logout.php
<?php
include("includes/db.php");
include("includes/head.php");
include("includes/search_box.php");
include("includes/left_sidebar.php");
//Allow access to session data
session_start();
//Redirect user to login page if they're not already logged in_array
if (!isset($_SESSION['user_id'])){
require('login_tools.php'); load_page();
}
//Clear existing session variables
$_SESSION = array();
session_destroy();
echo "<p>You are now logged out.</p>
<p><a href=login.php>Login again here</a></p>";
?>
session_start should always be the first line of any php page, even before including all the external pages.
Make session_start the first line of every page.

Session variables not being transported

I'm learnig PHP (as a hobby) and I wanted to build a simple login page to practice.
I have a form:
<form action="phpAction/checklogin.php" method="POST">
<p>Username:</p>
<input type="text" name="username">
<p>Password:</p>
<input type="password" name="password">
<br><br>
<input type="submit" value="Submit">
<br><br>
You don't have an account yet?
</form>
Posting to the php code:
<?php
// Starts a MySQLi connection to the database
include "../includes/mysqliConn.php";
// Starts a session to keep the user logged in
session_start();
// Posts the username and password from the form and stores it into a session variable
if (isset($_POST["username"]) && isset($_POST["password"])) {
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
} else {
die("You cannot be here!");
}
// Checks login
$checklogin = 'SELECT * FROM users WHERE username = $_SESSION["username"] AND password = $_SESSION["password"]';
$result = $conn->query($checklogin);
if ($result->num_rows = 0){
echo "<script language='javascript' type='text/javascript'>alert('Login and/or password wrong!');window.location.href='login.php';</script>";
die();
} else {
// Variable to other pages see that the user is logged in
$_SESSION["islogged"] = "true";
// Redirects to the homepage
header("Location: ../index.php");
}
?>
It sets the session variable "islogged" to true so that other pages can diplay user's information.
In the header of the website I have this:
<?php
if ($_SESSION["islogged"] == "true") {
echo "<a href='#'>Panel</a>";
echo "<a href='#'>Logout</a>";
} else {
echo "<a href='login.php'>Login</a>";
echo "<a href='#'> / </a>";
echo "<a href='signup.php'>Sign Up</a>";
}
?>
When the variable "islogged" is set to "true", the page should display the links Panel and Logout, instead of the Login and Signup ones. But I keep getting the login and signup.
It seems like the session variables are not being "transported".
Any kind of help is appreciated.
PS: Sorry for bad English :P
Thanks
As far as I know anything other then numbers must be enclosed in a ' ' . Just try this one
$checklogin = "SELECT * FROM users WHERE username ='".$_SESSION['username']."' AND password ='".$_SESSION['password']."'";
I hope this works.
To use $_SESSION variables, run session_start() first. The example that you have marked as "in the header of the web site," you're not running session_start() first.
http://php.net/manual/en/function.session-start.php
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

PHP Session destroy twice?

Upon entering the "secure" page, I have an if statement asking if the user is logged in, as shown below.
This statement baffles me as the outcome of both statements are the same, but it is the only way for me to end session when refreshing page. So if I change the statement to if (!session == user) {session_destroy} else { continue with session}, refreshing the page will have the session going.
edit The if/else statement in session.php is the one I do not understand. How can I have an if/else statement with two equal outcomes and yet receive two different outcomes in practice. As I enter my login credentials, I enter the session.php. If I refresh, I end up back at index.php. However, my statement claims that if I have session variables, then destroy session. If I do not have session variables, destroy session. What am I overlooking? edit
Secure page session.php below.
<?php
// To connection
require("includes/functions.php");
// Is the user logged in?
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
} else {
//Here is the funky part, why have if condition with two predicted equal statements, but have two different outcomes.
// If set, destroy session.
session_destroy();
} //Then the anything below should be secure.
?>
My functions.php (the included one) file is actually a connect to db with a session_start(). The login_process.php page looks as follows.
<?php
// Connection
require_once("functions.php");
//Once form has been clicked, the submitted name reappears, but first empty.
$submitted_username = '';
// IS form submitted?
if(!empty($_POST['login']))
{
// Find username
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
// Login bad first
$login_ok = false;
// Find user
$row = $stmt->fetch();
if($row)
{
// Check password
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If match, login good.
$login_ok = true;
}
}
// If allgood session start.
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
//Issue here?
$_SESSION['user'] = $row;
// Redirect user to secret page.
header("Location: session.php");
exit;
}
else
{
// Tell the user they failed
$login_failed = "<p class='clear floatleft'>Login Failed.</p>";
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
} ?>
The require_once in login_process.php is due to login_form.php being added as an include on every page. Thus always creating a session_start();. See login_form below.
<?php include('login_process.php'); ?>
<form action="" method="post">
<!-- Sign in form -->
<label>Username</label>
<input type="text" name="username" value="<?php echo $submitted_username; ?>">
<label>Password</label>
<input type="password" name="password" value="">
<input class="inline" type="submit" name="login" value="Login">
<input class="inline" type="submit" name="signup" value="Sign Up">
</form>
<?php if(isset($login_failed)) {
echo $login_failed;
}
?>
The form is picked up from a tutorial, please understand that I am not as of yet capable of producing such a login form rendering. I like to think that I understand the blocks of code by the comments I have created.
But I digest, I do not understand how the if/else statement in session.php can have two equal values and render differently. So any help on this particular subject would be greatly appreciated.
This question may be a duplicate, I have read so many questions regarding sessions that I feel blind to finding any help.
Thanks in advance.
Digress
Your code is doing exactly what it is written to do. Just as you think it is.
When a user inputs their credentials and is successful in login_process.php at -
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
//Issue here?
$_SESSION['user'] = $row;
// Redirect user to secret page.
header("Location: session.php");
exit;
}
else
{
The user is redirected to session.php to have their session destroyed. Why? Because the code says that if the user has nothing in $_SESSION['user']
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
then destroy the session.
OTHERWISE destroy session.
So no matter what the user session is destroyed. Successful or not.
The reason you don't get redirected until a refresh is because after you log in --successfully-- your session is destroyed. Then on refresh(of the same page) you satisfy the check for
if(!isset($_SESSION['user'])) {
//If user not set, destroy session.
session_destroy();
header("Location: index.php");
exit();
because $_SESSION['user'] no longer exists. Thus it redirects you to the homepage.
TL;DR session_destroy() cleared $_SESSION['user'] and a refresh on the same page causes user to clear first check of if statement.

Records Login Entries and Session State

How can I record the login entries and session state? I've search for source codes and ideas but I can't understand some of it. I want to ask a simple code through PHP. I have a code that can login user but does not need MySql database, and I want an idea how to RECORD LOGIN ENTRIES AND SESSION STATE connecting my PHP Login code. Or if you have other option code that need MySql database.
Here's the code:
"CONFIG.PHP"
<?php
$user = "admin";
$pass = "password";
?>
"INDEX.PHP"
<?php
include("config.php");
// Check form if is submited
if(isSet($_POST['trimite'])) {
// Check if user is equal with username and password from config.php
if($_POST['user'] != $user || $_POST['pass'] != $pass) {
echo "Sorry, your data is invalid";
} else {
// Open the session for store user logged
session_start();
// Setting the session
$_SESSION['logat'] = "da";
// Redirecting user to admin page if is logged
Header('Location: admin.php');
}
} else {
// Form
echo '<form action="" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="trimite">
</form>';
}
?>
"ADMIN.PHP"
<?php
include("config.php");
// Start session
session_start();
// Check if user is logged and existing session
if(isset($_SESSION['logat'])) {
// Content for user logged
echo "Welcome ".$user." :) - <a href='logout.php'>Logout</a>";
} else {
// Redirecting to login page
Header("Location: ./");
}
?>
Always put session_start() as the very first statement after <?php
It is okay to run session_start() even if the user is not logged in. session_start() should be the first statement.
Note that the header() command requires a lowercase h (not Header - that is wrong).
index.php
<?php
session_start();
include("config.php");
// Check form if is submited
if( isSet($_POST['user']) ) {
// Check if user is equal with username and password from config.php
if($_POST['user'] != $user || $_POST['pass'] != $pass) {
echo "Sorry, your data is invalid";
} else {
// Open the session for store user logged
// Setting the session
$_SESSION['logat'] = "da";
$_SESSION['username'] = $_POST['user'];
// Redirecting user to admin page if is logged
header('Location: admin.php');
}
} else {
// Form
$out = '
<form action="" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pass">
<input type="submit" name="trimite">
</form>
';
echo $out;
}
?>
admin.php -- Here is how to reference/use the username session variable:
<?php
// Start session
session_start();
include("config.php");
// Check if user is logged and existing session
if(isset($_SESSION['logat'])) {
// Content for user logged
echo "Welcome ".$_SESSION['username']." :) - <a href='logout.php'>Logout</a>";
} else {
// Redirecting to login page
header("Location: ./");
}
?>
Note that header can only be used if no data has been sent to the DOM yet. Sometimes that is very difficult to prevent. Here is an HTML tag that allows you to redirect to another page:
<meta http-equiv="refresh" content="0;url=http://example.com">
The number zero (before url= means the number of seconds to wait before redirecting the page.

How can I set the session with login use 2 file? Home > login > Home

How can I set the session with login use 2 file? Home > login > Home
did I do something wrong in my code?
Thanks.
home.php
<?php
session_start();
?>
<!DOCTYPE html>
<html><head><title></title></head>
<body>
<?php
if($_SESSION['account']){
print"login successful";
//do something
}
else{
print"login invalid";
print"
<form method=\"post\" action=\"login.php\">
account: <input type=\"text\" name=\"account\"><br>
password: <input type=\"text\" name=\"password\"><br>
<input type=\"submit\" value=\"login\">
</form>
";
}
?>
</body>
</html>
login.php
$account = mysql_escape_string($_POST['account']);
$password = mysql_real_escape_string($_POST['password']);
if($account == 'myaccount' && $password == 'mypassword'){
session_start();
$_SESSION['account'] = $account;
$_SESSION['password'];
print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">";
header("location: home.php");
exit();
}
else{
print"<meta http-equiv=\"refresh\" content=\"0;url=home.php\">";
header("location: home.php");
exit();
}
You are not storing any data on the $_SESSION array.
Try:
$_SESSION['account'] = true; // Or something else that evaluates to true and is relevant.
$_SESSION['password'] = 'please, anything but your password plaintext. think of the children';
That way, when you test for the result of the login operation on home.php:
if($_SESSION['account']){
print"login successful";
//do something
}
you can satisfy the condition.
Based on your script this :
$_SESSION['account'];
$_SESSION['password'];
Should be this:
$_SESSION['account'] = $account;
$_SESSION['password'] = $password;
But be aware please do not use this in a production site. this will not work to authenticate users.
You cannot use the session as the only method of logging a person in and keping them logged in. Sessions can easily be hijacked. a good user authentication system will:
encrypt the password
stored user information in the database
collect session information and set it
Now to keep a user logged in, each time they visit a new page you will use the seesion id, the passsword, the user ip, and session variables to authenticate the user and allow them to see the page. Basically you would create a function or a class to handle this in a secure manner.
Now for those that are just starting to learn php, there are a lot of great login scripts already out there. Any good site that Authenticates its users, starts with a really good user authentication system and then builds a site within that.
change line:
if($_SESSION['account']){
print"login successful";
}
by
if(isset($_SESSION['account']) && $_SESSION['account'] == true){
print"login successful";
}

Categories