Why is if (empty($_SESSION['gebruikersnaam']['wachtwoord'])) not working? - php

first off all my English is not very good. Sorry I do my best. I am developing a CMS system. I need an inlog system for it. If you are not logged in you can't view some of the pages. I created a php session of it but it doesn't work on the other pages... I will include some off the code I wrote.
On the page I check the username and password, I created the session like this. And worked with session to check username and password, so it works on that page.
<?php
session_start();
$_SESSSION['gebruikersnaam'] = $_POST['gebruikersnaam'];
$_SESSSION['wachtwoord'] = $_POST['wachtwoord'];
if(($_SESSSION['gebruikersnaam'] == 'admin')
&& ($_SESSSION['wachtwoord'] == 'admin123')) {
include("adminpanel.php");
} else {
echo "Uw gebruikersnaam of wachtwoord is foutief.";
}
?>
On my other pages I added this to check if the user is logged in. I seem to never get that I am logged in and I can't echo the session out. Here is the code!
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
If the conditional statement with the session works, I can redirect the user to the log in page if he is not logged in.
Thanks in advance you would help me a lot!

That's because of a slip of the tongue, its $_SESSION not $_SESSSION and also:
$_SESSION['gebruikersnaam']['wachtwoord'];
Is actually referring to 1 value, not two:
$data = array('gebruikersnaam' => array('wachtwoord' => 'mijnwachtwoord'));
echo $data['gebruikersnaam']['wachtwoord'];
Instead do:
if(!empty($_SESSION['gebruikersnaam']) || !empty($_SESSION['wachtwoord'])){
echo "not ingelogd";
}
However, you should only store a username and id in a session. Storing the password is a potential security breach and is not necessary.
You could also use something like this to scan for required values:
function required_session_fields(array $keys){
foreach($keys as $k){
if(!array_key_exists($k, $_SESSION) && empty($_SESSION[$k])){
return false;
}
}
return true;
}
if(required_session_fields(['gebruikersnaam', 'wachtwoord'])){
echo 'gelukt';
}
If you started the session and included a file, you can still access the $_SESSION variable. On every new server request, make sure the session is started.

On the other pages you must have
session_start();
before
if(!empty($_SESSION['gebruikersnaam']['wachtwoord'])) {
echo "not ingelogd";
}
However this variable $_SESSION['gebruikersnaam']['wachtwoord'] is never created. Currently you have created $_SESSION['gebruikersnaam'] and $_SESSION['wachtwoord']
Perhaps you meant to have something like
if(!empty($_SESSION['gebruikersnaam']) && !empty($_SESSION['wachtwoord'])) {
echo "not ingelogd";
}

Related

How to authenticate securely by session tokens and cookies? updated

I tried to write my own authentication method (school project), and I'm stuck.
Please advise, how to solve a secure authentication:
There is an index.php which contains everything that needs to be "protected". I will copy the relevant parts of my code here.
updated index.php
session_start();
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['PHPSESSID'])){
if ($_SESSION['PHPSESSID'] == $_COOKIE['PHPSESSID']){
$authStatus = true;
}
}
return $authStatus;
}
if(!checkUserAuth()){
include_once(dirname(__DIR__).'/admin/authentication/login.php');
exit();
}
If the checkUserAuth() determines, that there is no properly authenticated user, will include the login.php and stop the rest of the script.
updated login.php:
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
$_SESSION['PHPSESSID'] = $_COOKIE['PHPSESSID'];
$_SESSION['login_user'] = $_POST['user'];
What I imagine that might happen, is that if the login details are correct, the login.php sets a cookie, and refreshes the page. Then the index.php will detect the cookie, and skip the login part.
The login is pretty much figured out, and thanks to Juned, I think it is working now. However I don't know how secure is this?
On a scale from 1 to very, how wrong I am?
There are loads of ways of doing this. The below pseudocode is not the most efficient but should work and I don't think what you've done above will actually work.
Does this help?
login.php pseudocode
<?php
session_start(); // this function checks if there's a session ID already set, if not, sets one.
if(array_key_exists($username, $users) && password_verify($password, $users[$username])){
// do your login details checking here
// if login details correct
// set a flag in the $_SESSION superglobal and whatever else you want to store about the user like their username e.g.
$_SESSION["loggedIn"] = true;
$_SESSION["username"] = "$_POST['user']"; // better practice to fetch a clean version from your database
//else return user to login page
}
?>
index.php pseudocode
<?php
session_start(); // this will fetch the session ID and other variables that you might have set e.g. username, logged in status
function checkUserAuth(){
$authStatus = false;
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true){
$authStatus = true;
}
return $authStatus;
}
if(!checkUserAuth()){
// redirect to login page. e.g.
header('Location: login.php');
exit;
}
?>

Logged in value issue between PHP scripts

I am reading a lot regarding the best practice to monitor when a user is logged in or not.
Currently i am trying to use a variable in a session like below:
login.php
<?php
session_start();
//I set that variable to false
$_SESSION['LOGGED_IN'] = FALSE;
{follows some code that checks the username and the password provided by the user
in an HTML form with POST request against the records of the database. If a match is
found then it allows the user to proceed with the loggin}
if($statement->rowCount() = 1) //
{
session_regenerate_id(true);
$_SESSION['LOGGED_IN'] = TRUE;
header('Location: mainpage.php');
}
else
{
echo "wrong username or password";
}
?>
mainpage.php
<?php
session_start();
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
echo "You are now logged in!";
}
else
{
echo "You are not logged in. Please retry.";
}
?>
The problem is that when i use a correct pair of credentials SOMETIMES i log in getting the "You are now logged in!" message, and sometimes using the same credentials i get the "You are not logged in. Please retry.".
I've added that message in the else statement on purpose. Normally there i will insert a redirection to the login page.
I am getting confused because this is an error that i shouldn't have. In the login.php script i am making sure that in order to redirect to the mainpage.php the $_SESSION['LOGGED_IN'] = TRUE. So that value should be transferred to the mainpage.php as TRUE and not FALSE.
What am i missing here?
And a general question regarding loggin:
Is it better to keep the login value (TRUE or FALSE) in a session or use a table in MySQL with a flag indicating when a user is logged in or not?
Thanks!

Session is destroyed on page refresh in PHP

I am developing a web application using PHP in which a user initially has to sign in and view his content. I am using PHP sessions to maintain state. I encountered following problems:
Although I started the session on each page and after relevent session variables are set, the session is destroyed each time the page is refreshed or when I browse the same URL on a different tab.
I need the user to be redirected to his content page when the user browsed login page with he has already logged in.
I'm really new to PHP, So I have no idea how to solve these problems. I referred several questions in the stackoverflow, but they all say that sessions are not destroyed on page refresh. I could not understand what's wrong with my page. Any solution with explaination is greatly appreciated.
Login page
<?php
session_start();
class Sessions{
public static function setSessionState($userdata){
unset($userdata['password']);
unset($userdata['timestamp']);
$_SESSION['user']=$userdata;
}
}
if(isset($_POST['username']) && isset($_POST['password'])){
$dbcon = new DBConnection();
$dbcon->connect();
$username= strip_tags(stripslashes(trim($_POST['username'])));
$password = strip_tags(stripcslashes($_POST['password']));
echo "<script>alert($username);</script>";
$result = $dbcon->getUser($username,$password);
if(mysqli_num_rows($result)==1){
$user = $dbcon->getUserData($result); #getUserData function accepts mysqli result as an input and returns a row(array) of user details.
if(isset($user)){
Sessions::setSessionState($user);
header("location:index.php");
}
else{
echo "user variable is not set!!!";
}
}
else if(mysqli_num_rows($result)==0){
echo "Login error! Username or Password incorrect!";
}
else{
die("Unknown Error occured!");
}
}
............
Index page(in which user's private content is visible)
<?php
session_start();
if(isset($_SESSION['user'])){
print_r($_SESSION['user']);
}
else{
echo "session variable not set";
}
?>
Thank you.
I finally found the answer which is actually my bad. I didn't mention the last part of the index.php file as I though that part is irrelevant.In that part I have a part,
<form action="<?php session_destroy(); ?>">
After commenting that session_destroy() method call, I could solve my problem and keep session alive.
Sorry for incomplete code.
try this
class Sessions{
public static function setSessionState($userdata){
if ( !isset($_SESSION['user']) ) {
$_SESSION['user'] = $userdata;
}
}
}

have to refresh page after log out to get the correct code

$loggedin = false;
if ($_SESSION) { //user loggedin
$loggedin = true;
...//get token
}
...
if($loggedin){
echo 'Hi '.$user['name'];
}
else{
echo 'Please log in';
}
...
I suppose the web page will display "please log in" when I log out. But it says "undefined $user variable at /src/myproject/index line 80". And after I refresh the page, it says "please log in".
What is the problem here? Thank you for your help.
From what I can tell from your pseudo code, you have some sort of key in the $_SESSION variable that says the user is logged in.
For demonstration, let's assume you do something like... After the user logs in, you assign $_SESSION['user'] = an array of user information. One of those keys is 'name'.
So, your code should look something like this
$loggedin = false;
if (isset($_SESSION['user'])) {
$loggedin = true;
}
if ($loggedin) {
echo "Hi " . $_SESSION['user']['name'];
}
else {
echo "You are not logged in."
}
Please keep in mind this is just a solution for your code sample you posted. To do this properly, I would suggest the following changes:
create a class that handles authentication
create methods in that class to determine if the user is logged in or not
create methods to return the current logged in user.
This will make your code more extensible, reuseable and easier to follow in the future.
Best of luck.

Php login system, how to secure it

A php newbie here.
Below is the code I'm using to build a login system to enter mypage.php
It's working great but it is quite naive, anyone can type mypage.php in the url and avoid the login page.
How can I build it more secure?
Thanks a lot!
if(isset($_POST['submit'])) {
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
$sql = "SELECT * FROM login WHERE user='".$user."'";
$res = $this->new_db->select($sql);
$row = $this->new_db->get_row($res);
if (isset($row)) { //user exists?
if($row["pass"] == $pass){
$_SESSION['userId'] = $row['user'];// TRYING WITH SESSIONS
header("Location: mypage.php");
} else {
echo "wrong pass";
}
} else {
echo "user does not exist";
}
}
Then in mypage.php
if(isset($_SESSION['userId'])) {
//contents
} else {
echo "there's an error";
}
It is printing "there's an error"
why??
Thanks a lot
Three things:
Don't store passwords in plain text. Given this code, I can only assume that's what you're doing. You should store the passwords hashed, hash the password the user enters, and compare those.
You have a SQL injection vulnerability. Any time you're receiving input from the user that's destined for a database query, at the very least you should wrap it in mysql_real_escape_string().
On the logged-in page (on any logged-in page) you'll want to track whether or not the user is logged in. One simple way to do this is to have the login form set a $_SESSION value indicating the user's current logged-in status. Then on any page which requires a user to be logged in, check for that value. If it exists, they've previously logged in. If it doesn't, they haven't. It's simple, but good enough to get your going for what you need.
yes, there might be sql-injection in your code
in order to prevent you may use mysql_real_escape_string function
Check my answer here i posted before some time, which explains how you should go with login systems.
Open-source rich HTML editor
You will need to put something in mypage.php to check to see if the user is "logged in". I have done this in the past with the Zend Auth module from the Zend Framework. The cool thing about it is it can be used alone, (you don't have to make a whole Zend Framework site to use the Auth module). I used the Zend Auth Page to figure out how to use it.
Then, once I setup the auth session using the Zend Session, I just checked at any other page to see if the user was "logged in" with something like this:
private function _loggedIn()
{
$loggedIn = false;
$Namespace = new Zend_Session_Namespace('Zend_Auth');
foreach ($Namespace as $index => $value) {
$loggedIn = ($value->user_id);
}
return $loggedIn;
}
First of all, you have to protect your mysql query from sql injection. This can be achieved by adding mysql_real_escape_string like that:
$user = mysql_real_escape_string($_REQUEST['user']);
Then, if you don't want users to be able to visit mypage.php without being logged in, you should set some cookie in your login script if the login is successful, and then, on mypage.php, check that cookie to see if it matches in your database. Something like that:
login.php:
if($row["pass"] == $pass){
setcookie("userid",$user);
setcookie("passhash",sha1($pass));
...
mypage.php
$res = mysql_query("select * from login where user='".mysql_real_escape_string($_COOKIE['userid'])."' limit 1");
$row = mysql_fetch_assoc($res);
if($_COOKIE['passhash'] == sha1($row['pass']))
{
die("logged in OK");
}
else
{
die("please log in");
}
if (isset($_POST['submit'])) {
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
$sql = "SELECT user FROM login WHERE user='".mysql_real_escape_string($user)."' AND pass=SHA1('".mysql_real_escape_string($pass)."')";
$res = $this->new_db->select($sql);
$row = $this->new_db->get_row($res);
if ($row['user'] != "") { //user exists?
header("Location: mypage.php");
}else{
echo "username and password combination is wrong";
}
}

Categories