I am getting Notice: Undefined index: loggedin in when using SESSION - php

When a user is successfully authenticated, s/he is either redirected to register.php if the user has not yet signed up for training.
If the user has already signed up for training, s/he is redirected to registered.php to view/modify his or her training classes.
So far, this works fine.
Problem is if user attempts to go directly to register.php or registered.php, s/he gets into any of the web pages without logging in first.
This is what I am trying to prevent but I keep getting the following error message:
Notice: Undefined index: loggedin in .... on line 3
Please log in first to see this page
Here is what I am using so far and thanks for your help.
//login.php
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// hash to sanitize the input further
$pass = md5($pass);
$tSQL = "SELECT u.empl_first, u.username FROM users u inner join Training t on u.Employee_Id = t.Employee_ID WHERE USERNAME = ?
and PASSWORD = ? ";
$params = array($user, $pass, $params);
$sqll = sqlsrv_query($con, $tSQL);
if ($objResult = sqlsrv_fetch_array($sqll, SQLSRV_FETCH_ASSOC)) {
$firstname = $objResult["empl_first"];
$_SESSION["firstname"] = $objResult["empl_first"];
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $user;
header('location:registered.php');
}
else
header("location:register.php?user='".ms_escape_string($user)."'&pass='".ms_escape_string($pass)."' ");
sqlsrv_close($con);
?>
//register.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
echo "Please log in first to see this page";
}

There are 2 mistakes:-
In login.php start the session using session_start(); at the top of the script, so that the code that sets variables in $_SESSION will work.
In register.php change the IF statement from
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true)
To
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true)
then the IF will not test $_SESSION['loggedin'] != true if the variable is found to not exist by the first part of the IF i.e. !isset($_SESSION['loggedin'])

On login.php have session_start(); somewhere on the top.
On each script that you use the session you must have it.

Related

PHP Session variables not persisting

I'm creating a site that uses sessions to store login details - I know its a bad security practice but that'll be dealt with later; for now I just need to fix this issue. Page 1 gets the login details from a login form and stores them in a session. Page 2 is meant to display those variables, but I get these errors when trying to access the variables:
Notice: Undefined index: email in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 10
Notice: Undefined index: password in /customers/0/4/0/my-domain.com/httpd.www/upload-photo.php on line 11
Here is the code - I've left off the unrelated parts:
Page 1
session_start();
var_dump($_SESSION);
ini_set('display_errors',1);
error_reporting(E_ALL);
// Just logged in
if($_POST["email"] != "" || $_POST["password"] != ""){
$email = strtolower($_POST["email"]);
$password = md5($_POST["password"]);
$_SESSION["email"] = $email;
$_SESSION["password"] = $password;
//echo "setting details from http post";
}else{
// Just redirected to this page
$email = $_SESSION["email"];
$password = $_SESSION["password"];
}
And page 2 where I'm getting the errors mentioned above:
session_start();
ini_set('display_errors',1);
error_reporting(E_ALL);
var_dump($_SESSION);
$_SESSION["advert"] = $_GET['id'];
echo $_SESSION["email"];
echo $_SESSION["password"];
I've searched SO and have made sure there are no spaces or whatever before my session_start();
By the way, if it helps my domain company that I'm using is One.com
$_SESSION["email"] and $_SESSION["password"] are set in the if, so in the case it is skipped you get this undefined indexes error (as elements with this indexes were not defined anywhere before).To get rid of this Notice you can use isset() function(also use it to validate $_POST user input). Example :
echo isset($_SESSION["email"]) ? $_SESSION["email"] : 'There is no element with key "email"';
P.S. Validating your POST input :
if(isset($_POST["email"]) && isset($_POST["password"])){}
Change condition to:
if(isset($_POST['email']) && isset($_POST['password'])){
//do login
}
else {
echo " Plese enter email and password";
}
For full:
Login.php
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(isset($_POST['email']) && isset($_POST['password'])){
$_SESSION['email'] = $_POST['email'];
$_SESSION['password'] = $_POST['password'];
}
else {
echo "Please enter email and password";
}
//here must be form to login
Logged.php:
<?php
//here must be totaly clear, nothing can't be here
session_start();
if(!isset($_SESSION['email']) && !isset($_SESSION['password'])){
header("Location: Login.php?err=Please login to use members area");
}
else {
echo "You are logged in as:". $_SESSION['email'];
}
I solved the problem. When I was on one page I was on www.domain.com/page1 but when I was on the other page there was no www - domain.com/page2. This meant that session variables were not persisting. To fox this, I need to edit the htaccess file to redirect to www if there is no www in the URL.

Trying to login via php not working scripts

Hi I am trying to get the user signed in via sessions, here is my code it was working before now it isn't i didnt even change the code.
profile.php (to show after logged in)
<?php
ob_start();
session_start();
$userName = $_SESSION['username'];
$userid = $_SESSION['userid'];
if(isset($_GET['session'])) {
$currentSessionID = $_GET['session'];
$currentSessionID = md5(md5(md5($currentSessionID)));
session_id($currentSessionID);
header("Location:profile.php");
return;
}
if(!isset($userName)){
echo "OUT";
return;
}
...
scripts/signin.php
ob_start();
session_start();
include"config.php";
echo "here";
// check for required fields
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Username']) && isset($_POST['Password'])) {
$user = mysql_real_escape_string($_POST['Username']);
$pass = mysql_real_escape_string($_POST['Password']);
$decrypt = md5(md5(md5($pass)));
$ensure = "select * from userinfo WHERE Username = '$user' and Password='$decrypt' and status='1'";
$result= mysql_query($ensure);
if(mysql_num_rows($result) > 0) {
echo "here2";
$entry = mysql_fetch_array($result) or die(mysql_error());
$_SESSION['username'] = $entry['Username'];
echo $entry['Username'];
$_SESSION['userid'] = $entry['Id'];
$currentSessionID = session_id();
$currentSessionID = md5(md5(md5($currentSessionID)));
header("Location: http://www.myprocity.com/profile.php?session=".$currentSessionID);
echo "here3";
the reason why im passing in the session id is because im trying to only keep sign in and sign up HTTPS while the other pages HTTP so I can show Google ads, does anyone know how to implement this without security issues (perfectly)
it always goes to OUT even when $_SESSION is my username (database is correct)
In profile.php you are checking for the presence of a session ID, and changing the session ID if you find it. You are doing this after you've set up a session with session_start(), but the PHP manual specifically says you must call session_id() before session_start() for this to work.
You're also hashing $_GET['session'] before sending it, and again before using it. The session ID you're trying to use in profile.php won't match the session ID used in signin.php
The result is that $_SESSION does not have the data in it you are expecting.
You need to rationalise your use of session_id(), and ensure the correct value is passed from page to page. All the hashing with md5() is just complicating matters - drop it. Realistically, I don't see why you need anything more than session_start() at the top of each page and let PHP handle the sessions. You may have an argument for doing what you're doing, but your solution simply won't work.

PHP Login not protecting page

I know this subject has been covered a ton, and I have looked and searched so I think I am missing something basic.
I have a Username Password log in system that is setup as:
Login page: set to Action - checklogin.php
checklogin.php - checks against the database for username and password, and then in the header brings them to their custom URL, which is in column 3 of the database. So user1 goes to folder1/, user2 goes to folder2/, etc.
It seems to work fine, but lets say I am logged in as user1 (URL /folder1/), it allows me to enter '/folder2/' in the URL window, and that folders index file comes up.
So basically if I am logged in any username, I can pull up the other users folder/index.php file.
So I think somehow the code on the index.php page is not validating the users correctly.
CODE (top is fine, connecting to DB, etc, so I left that out) :
checklogin.php:
// Define $username and $password
$username=$_POST['username'];
$password= $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
// Register $username, $password and redirect to file "index.php"
session_start();
$_SESSION[$username];
$_SESSION[$password];
$_SESSION['loggedin'] = true;
$_SESSION[$id];
$row = mysql_fetch_assoc($result);
$result = mysql_query("SELECT folder FROM users2");
$_SESSION['folder'] = $row['folder'];
if( isset($username) ) {
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
header('Location: clients/'. $row['folder'].'/index.php');
exit();
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
}
?>
On the receiving URL index.php page:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
I have tried many other variations of the receiving "Protect Page" code, but none seem to work correctly. Is it the receiving code or the checklogin code??? I feel I am missing something obvious.
Thanks in advance, any take on this will be appreciated. - Randy
You need to add additional checks in the protected pages; not only do you need a logged-in user, you also need to check the requested path and see if the user has access to that.
Something like (for example...):
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true
|| stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
Apart from that you should never store plain-text passwords and you should really switch to PDO (or mysqli) and prepared statements with bound variables.
Edit: Another solution to make clear what is happening:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit();
}
elseif (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// $_SESSION['folder'] is not found in the path,
// not user's folder, go to own folder
header('Location: /clients/'. $_SESSION['folder'].'/index.php');
exit();
}
else
{
// show page of user
}
your using a lot of unnecessary !==
replace most of those with !=
also change
if($count==1){
to
while($count>=1){
change
if( isset($username) ) {
to
if( isset($username) && $username != "" && $username != NULL ) {
Var_dump $result, make sure it contains what you want, you've got it listed two times.
when you reference a variable inside a session I'd recommend double/single quoting it.
Do yourself a favor and avoid magic quotes and mssql() entirely. Switch to pdo or MYSQLI
if (!isset($_SESSION['loggedin']) |$_SESSION['loggedin'] !== true)
if (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// not logged in, move to login page
header("location:../../login.php"); exit; } – RandyS just now edit

PHP log in error undefined index

I am trying to log in using this code :
session_start();
require "connect.php";
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrow = mysql_num_rows($query);
if($numrow!=0)
{
while($row = mysql_fetch_assoc($query))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
if($username==$db_username&&$password==$db_password)
{
//echo 1;
header("Location: members.php");
$_SESSION['username']=$db_username;
}
else echo 0;
}
else die("That user doesn't exist");
}
else die("Please enter a username and password");
upon successful log in it should take me to members.php :
session_start();
if($_SESSION['username']) <------ this is line 5
{
echo "20730312";
echo " You are logged in as: ".$_SESSION['username'];
echo "<p><a href='logout.php'>Click here to logout</a>";
}
but when i request members.php in my application it gives me :
Notice: Undefined index: username in E:\Program Files\xampp\htdocs\adddrop\members.php on line 5
note that i am using android webview to request members.php after successful log in, is this right ? what am i doing wrong ?
On a side note: you have an SQL injection there. Might want to read more: http://en.wikipedia.org/wiki/SQL_injection
The problem you are facing is that the username is not always POST'd (when you just load the page first time):
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
That should fix it. Basically, I check if the POST index is set, and only if it is I try to access it, otherwise I set it to null.
Also, you might want to do it like this:
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($username) . "'");
That prevents the SQL injection vulnerability.
And also add exit;:
header("Location: members.php");
$_SESSION['username']=$db_username;
exit; // Add this.
Same as always. You're not POSTing to the URL. Verify the URL you're attempting to POST to.
perhaps this:
header("Location: members.php");
$_SESSION['username']=$db_username;
should be changed to (reverse):
$_SESSION['username']=$db_username;
header("Location: members.php");
As it says, you don't have the specified data from POST. Make sure your form action is right and you're filling out the username.
Also, you might want to consider hashing your passwords. From what I can see here you compare plain text passwords (or you're already getting hashed passwords to your script, which would be ok).

PHP session_start question

So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.

Categories