Jump to content

Sessions? How to secure pages for only logged in users


Go to solution Solved by jcbones,

Recommended Posts

So I was searching around and I found out about PHP Sessions, I am new to PHP coding and I have tried to google it but its to no avail, I'm probably doing something wrong or I'm just dumb but heres the code.


Index ( Login page ): 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login</title>
        <style>
            @import "css/login.css";
        </style>
    </head>

    <body>
        <div class="body"></div>
        <div class="grad"></div>
        <div class="header">
            <div><b>User<span>Login</span></b></div>
        </div>
        <br>
        <form method="post" id="login-form" name="login-form" action="panel.php"><div class="login">
            <input type="text" placeholder="username" name="user" required><br>
            <input type="password" placeholder="password" name="password" required><br>
            <input type="submit" name="login" id="login" value="login" />
        </div></form>
        <div class="forgotpw"><span title="You will need your account email!"><a href="recover.php" class ="b">Forgot Password?</a></span></div>
<?php  /* Temporary until my database is finished */
        $users = array(
            "User1" => "123",
            "User2" => "1234",
            "User3" => "1235"
        );
        
        $user = null;
        $password = null;
        if(isset($_POST['user']) && trim($_POST['user']) !=''){
            $user = trim($_POST['user']);
        }

        if(isset($_POST['password']) && trim($_POST['password']) !=''){
            $password = trim($_POST['password']);
        }
        
        if($user && $password) {
            if(array_key_exists($user, $users)) {
                if($password == $users[$user]) {
                echo "<div class="."success".">Successful. Redirecting you in 3 seconds.</div>";
                echo "<meta http-equiv="."refresh"." content="."3;URL=panel.php".">"; 

                } else {
            echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
            }
            } else {
            echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
            }
         } 
?>

    </body>
</html>

Panel.php: 
 

<!DOCTYPE html>
<html lang="en">

<head>
        <meta charset="UTF-8">
	<title>Admin Panel</title>    
        <style>
            @import "css/panel.css";
        </style>
</head>
<body>
</body>
</html>

1 - Four posts at once? Really?

 

2 - You showed us a bunch of code.

 

3 - You mentioned that you just found out about the existence(?) of Sessions in PHP.

 

4 - You didn't ask a question.

EDIT - My bad. After posting I re-read the topic heading and see that there is a (sorta) question there. So - use my reference to the manual to learn about sessions.

As for how one writes a secure login script there is lots of info out there and samples too. Everyone does their logins differently so do some research and pick the one that makes sense to you and then read up on the functions/features it uses to learn from it and then ask for tips once you have written something.

 

A good point of reference as a newcomer to PHP would be the official PHP manual. Go to 'php.net'. Plenty of knowledge there for you to read up on.

 

 

PS - It is good practice to separate your html & JS code from your php code - for logical sense and readability and maintenance purposes.

Edited by ginerjm

1 - Four posts at once? Really?

 

2 - You showed us a bunch of code.

 

3 - You mentioned that you just found out about the existence(?) of Sessions in PHP.

 

4 - You didn't ask a question.

 

Is there something you want to know? A good point of reference as a newcomer to PHP would be the official PHP manual. Go to 'php.net'. Plenty of knowledge there for you to read up on.

 

 

PS - It is good practice to separate your html & JS code from your php code - for logical sense and readability and maintenance purposes.

1. I clicked submit and the page was endlessly loading so I clicked it again which posted it multiple times

2. I'm not even sure what works

3. I'm not sure how to use the sessions/how to create them.

4. I'm asking how to use/create the sessions

1. I clicked submit and the page was endlessly loading so I clicked it again which posted it multiple times

 

Don't worry; you're not alone. Note that I removed the duplicate posts.  :happy-04:

 

 

3. I'm not sure how to use the sessions/how to create them.

4. I'm asking how to use/create the sessions

 

Perhaps the examples found here will help:

http://php.net/manual/en/session.examples.basic.php

 

Note that you can use $_SESSION variables just like you use $_POST and $_GET. You just need to make sure you call session_start() before using the variables. More information can be found here:

http://php.net/manual/en/function.session-start.php

  • Like 1

I think you'll need to look at line 42.  The condition will never be met... Here's why.  The keys for $users array are string type with a value of "User1, User2 and User3".  However the function array_key_exists will compare your form $_POST['user'] value (assigned to $user).  So as an example, it should compare the string "123" to the strings "User1, User2, User3"... It should return false.  Try this instead:

$pass=null;
foreach($users as $key=>$value) { //compare users array to form field user
  if($value==$password) $pass=$key; //assign the $users[$key] to $pass
}

if ($pass!=null) { //should be something like User1, User2 or User3
$_SESSION['user']=$users[$pass]; //assign users password to session
}

/* continue on with your processing */

Then on subsequent pages

session_start();
if(!isset($_SESSION['user'] || empty($_SESSION['user']) {  //not set or empty value
  session_destroy();
  header("Location: error.php"); //sent to UI error reporting
  exit();
}
Edited by rwhite35
  • Like 1
 

 

$pass=null;

foreach($users as $key=>$value) { //compare users array to form field user
if($value==$user) $pass=$key; //assign the $users[$key] to $pass
}

if ($pass!=null) { //should be something like User1, User2 or User3
$_SESSION['user']=$users[$pass]; //assign users password to session
}

/* continue on with your processing */

 

So on this I would just replace line 42? I'm confused on the assigning, could you apply it to my code so I can see why it should be that way? I see a little bit of it, I just don't know how to place it in my code.
Edited by FatesCall

Fortunately, its a slow day...  Keep in mind your original post mentioned sessions, you'll still want to assign the password or user to the session as described above.

$user = "john doe";
$password = 1234;
$pass=null;
$users = ["User1" => "123","User2" => "1234","User3" => "1235"];

if($user && $password) {
    foreach($users as $key=>$value) {
	if($value == $password) $pass=$key;
    }
    if($pass != null) {
       //assign to session variable here, before you redirect,
       //assumes session started immediately after PHP open tag
       $_SESSION['user']=$users[$pass];
       echo "<div class="."success".">Successful. Redirecting you in 3 seconds.</div>";
       echo "<meta http-equiv="."refresh"." content="."3;URL=panel.php".">"; 
    } else {
       echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
    }
} else {
    echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
}
Edited by rwhite35

 

Fortunately, its a slow day...  Keep in mind your original post mentioned sessions, you'll still want to assign the password or user to the session as described above.

$user = "john doe";
$password = 1234;
$pass=null;
$users = ["User1" => "123","User2" => "1234","User3" => "1235"];

if($user && $password) {
    foreach($users as $key=>$value) {
	if($value == $password) $pass=$key;
    }
    if($pass != null) {
       //assign to session variable here, before you redirect,
       //assumes session started immediately after PHP open tag
       $_SESSION['user']=$users[$pass];
       echo "<div class="."success".">Successful. Redirecting you in 3 seconds.</div>";
       echo "<meta http-equiv="."refresh"." content="."3;URL=panel.php".">"; 
    } else {
       echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
    }
} else {
    echo "<div class="."warning".">Error: Username or Password is incorrect!</div>";
}

Everytime I load this, it reads it sends the Warning html without even inputting anything,

What does your code currently look like?

 

Based on your original post, the script to process the form submission appeared to be embedded within the page that displays the form. However, the form submission is sent to "panel.php". So it seems like the form information would never get processed.

  • Like 1

What does your code currently look like?

 

Based on your original post, the script to process the form submission appeared to be embedded within the page that displays the form. However, the form submission is sent to "panel.php". So it seems like the form information would never get processed.

Its the same but i added in the new code and remove "action=panel.php" from the form

Note that it may help to see your new code. What we assume is done doesn't always match with what was actually done.  :happy-04:

 

With that said, did you change the following lines:

$user     = "john doe";
$password = 1234;
 
To something like this:
$user     = (isset($_POST['user']))     ? trim($_POST['user'])     : '';
$password = (isset($_POST['password'])) ? trim($_POST['password']) : '';
 
If not, the code is always going to use the hard-coded values.
Edited by cyberRobot

 

Note that it may help to see your new code. What we assume is done doesn't always match with what was actually done.  :happy-04:

 

With that said, did you change the following lines:

$user     = "john doe";
$password = 1234;
 
To something like this:
$user     = (isset($_POST['user']))     ? trim($_POST['user'])     : '';
$password = (isset($_POST['password'])) ? trim($_POST['password']) : '';
 
If not, the code is always going to use the hard-coded values.

 

ok ill post the code as soon as i wake up tomorrow

 

EDIT:

 

index.php: http://hastebin.com/fisodifino.php

Edited by FatesCall

It looks like $pass is never set to "null"; so the following line should always equate to true:

if ($pass != null) {

You could try something like this:

       if ($user && $password) {
            foreach ($users as $key => $value) {
                if ($value == $password) {
                    $pass = $key;
 
 
                    //assign to session variable here, before you redirect,
                    //assumes session started immediately after PHP open tag
                    $_SESSION['user'] = $users[$pass];
                    echo "<div class=" . "success" . ">Successful. Redirecting you in 3 seconds.</div>";
                    echo "<meta http-equiv=" . "refresh" . " content=" . "3;URL=panel.php" . ">";
                }
            }
            if (!isset($pass)) {
                echo "<div class=" . "warning" . ">Error: Username or Password is incorrect!</div>";
            }
        } else {
            echo "<div class=" . "warning" . ">Error: Username or Password is incorrect!</div>";
        }

Note: session_start() needs to be called before anything is outputted to the screen. In other words, it needs to be called before the doctype tag.

It looks like $pass is never set to "null"; so the following line should always equate to true:

if ($pass != null) {

You could try something like this:

       if ($user && $password) {
            foreach ($users as $key => $value) {
                if ($value == $password) {
                    $pass = $key;
 
 
                    //assign to session variable here, before you redirect,
                    //assumes session started immediately after PHP open tag
                    $_SESSION['user'] = $users[$pass];
                    echo "<div class=" . "success" . ">Successful. Redirecting you in 3 seconds.</div>";
                    echo "<meta http-equiv=" . "refresh" . " content=" . "3;URL=panel.php" . ">";
                }
            }
            if (!isset($pass)) {
                echo "<div class=" . "warning" . ">Error: Username or Password is incorrect!</div>";
            }
        } else {
            echo "<div class=" . "warning" . ">Error: Username or Password is incorrect!</div>";
        }

Note: session_start() needs to be called before anything is outputted to the screen. In other words, it needs to be called before the doctype tag.

Still results in the warning being shown as soon as I run the webpage

Still results in the warning being shown as soon as I run the webpage

 

Are you referring to the "Warning: session_start(): Cannot send session cache limiter - headers already sent..." warning? If so, session_start() needs to be called before outputting anything to the screen. Even a displaying white space before the call will trigger the warning.

 

Note: session_start() needs to be called before anything is outputted to the screen. In other words, it needs to be called before the doctype tag.

 

Are you referring to the "Warning: session_start(): Cannot send session cache limiter - headers already sent..." warning? If so, session_start() needs to be called before outputting anything to the screen. Even a displaying white space before the call will trigger the warning.

http://hastebin.com/ijucoqetus.php <--- Still throwing the error invalid logins

http://hastebin.com/ijucoqetus.php <--- Still throwing the error invalid logins

I guess you are referring to the "Error: Username or Password is incorrect!" being shown when you load your login form. This is showing because PHP is checking the username/password without the form  being submitted. You only want PHP check the username/password when the form has been submitted. To do so you can wrap the if ($user && $password) block of code within another if statement which checks to see if a POST request has been made. Example

// Only check the username/password when on POST request
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
   $user     = trim($_POST['user']);   
   $password = trim($_POST['password']);
   if($user && $password)
   {
      ... check username/password here ...
   }
}
Edited by Ch0cu3r

 

I guess you are referring to the "Error: Username or Password is incorrect!" being shown when you load your login form. This is showing because PHP is checking the username/password without the form  being submitted. You only want PHP check the username/password when the form has been submitted. To do so you can wrap the if ($user && $password) block of code within another if statement which checks to see if a POST request has been made. Example

// Only check the username/password when on POST request
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
   $user     = trim($_POST['user']);   
   $password = trim($_POST['password']);
   if($user && $password)
   {
      ... check username/password here ...
   }
}

Could this also be fixed by using the action="login-response.php" in the form and creating its own php form for the validation?

Yes, you can submit the form to a different file if you like. You still only want to to check the username/password when the form has been submitted, as per my code example.

I think there is something wrong in the code checking the username/password because I can use any combination with the password 123 to get in.

 

EDIT: http://hastebin.com/ehihuqojam.php <--- Login PHP

Edited by FatesCall


FatesCall, here is something to play with, fully commented, and working.

Maybe this will help you understand flow

 

login.php

 

 

<?php //No white space or BOM before this tag.
session_start(); //start the sesson.
if(isset($_SESSION['login']) && $_SESSION['login'] == true) { //if the session is set, and session login is set to true.
echo 'Thank you for logging in!'; //tell them that they are logged in.
$_SESSION['login'] = false; //for testing purposes, I then disable the login.
} else { //if we haven't logged in, then show the form.
?><form method="post" id="login-form" name="login-form" action="process.php"><div class="login">
            <input type="text" placeholder="username" name="user" required><br>
            <input type="password" placeholder="password" name="password" required><br>
            <input type="submit" name="login" id="login" value="login" />
        </div></form>
<?php 
}
?>  
Edited by jcbones
  • Like 1
  • Solution

#continue from above *CHROMIUM AHHHHHH*

 
process.php
 


<?php //no whitespace, no BOM must come before this line.
session_start();  //start the session.
define('MYSITE' , $_SERVER['SERVER_NAME']); //define what our site is.
$_SESSION['login'] = false; //we are NOT logged in.
if($_SERVER['REQUEST_METHOD'] == 'POST') { //if a POST request has been made.
$_POST = array_map('trim',$_POST); //trim the data.
if(!empty($_POST['user']) && !empty($_POST['password'])) { //if the user and password are NOT empty.
$users = ["User1" => "123", "User2" => "1234", "User3" => "1235"]; //list our users in array.
if(isset($users[$_POST['user']]) && $users[$_POST['user']] == $_POST['password']) { //if the password matches for the user entered.
$_SESSION['login'] = true; //log the user in.
header('Location: http://' . MYSITE . '/login.php'); //send the user to panel.php
exit(); //stop further execution of script.
} else { //if the username and/or password is wrong.
header('Location: http://' . MYSITE .'/error.php?reason=wp'); //send them to login_error.php with a reason code.
exit(); //stop the script.
}
}
header('Location: http://' . MYSITE . '/error.php?reason=nv'); //if the user or password was empty, send to login_error.php with reason code.
exit(); //exit the script.
}
 
error.php
 


<?php
if(isset($_GET['reason'])) { //if there is a reason to be here (should be the only reason we are here).
switch($_GET['reason']) { //run a switch.
case 'nv': //if the reason is nv (not valid).
$message = 'You must enter a username and a password.'; //set the message.
break; //break the switch to keep it from going further.
case 'wp': //wp (wrong password/username).
$message = 'You entered a wrong username and/or password.';
break;
}
}
//echo the message, redirect in 5 seconds.
echo '<html><head><meta http-equiv="refresh" content="5;URL=login.php"></head><body><div>' . $message . '</div></body></html>';
 
 
 
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.