PHP - Session_Destroy upon pressing Back button
Asked Answered
G

3

6

Here is my issue:

I have a login page called login.php (containing no HTML code). When the user types in his credentials correctly he's redirected to a specific page; we'll say test.php for this example. The only links on that page logout of the current session, and return the user to index.html.

My problem is that if the user presses the back button, it goes back to login.php and you get a blank page. If you navigate away from that blank page you have no way to get back to test.php thus no way to logout of that session.

My original idea was to disable the back button navigation with Javascript. Eventually I figured out that wouldn't work, because if the user found a way to get out of that page without logging out, they would be stuck in that session and login.php would be blank.

So is there any way to end the current session if that back button is pressed? Or if login.php is reloaded? I'm not too familiar with PHP so a detailed explanation would be greatly appreciated.

Here is the code for the login page:

    <?php
    /**
     * The idea of this application is to secure any page with one link. I know some of the professionals
     * will agree with me considering the way it has been done, usually you wouldnt put any other information such as
     * HTML/CSS with a class file but in this case its unavoidable. This is to make it easier for the non techys to use.
     * @author John Crossley <[email protected]>
     * @version Version 2
     **/

            // Turn off error reporting.
            error_reporting(0);

            # Start a new session, regenerate a session id if needed.
            session_start();
            if (!isset($_SESSION['INIT'])) {
                session_regenerate_id();
                $_SESSION['INIT'] = TRUE;
            }

            class JC_fsl {

        public static $_init;
        protected $_users = array();
        # Script configuration
        protected static $_script_name;
        protected static $_admin_email;
        protected static $_admin_name;
        private static $_version = '{Version 2.0.1}';

        protected function __construct() {

            if (!isset($_SESSION['LOGIN_ATTEMPTS']))
                $_SESSION['LOGIN_ATTEMPTS'] = 0;

            // Default user admin added.
            $this->_users = array(
                array(
                    'USERNAME' => 'admin', 
                    'PASSWORD' => 'master13', 
                    'EMAIL' => '[email protected]', 
                    'LOCATION' => 'master.php')
                );
        }

        public function __toString() {
            return 'SCRIPT NAME :: ' . self::$_script_name . "<br />" .
            ' ADMIN EMAIL :: ' . self::$_admin_email . "<br />" .
            ' ADMIN NAME :: ' . self::$_admin_name . "<br />" .
            ' FSL VERSION :: ' . self::$_version;
        }

        /**
         * This method allows you to peek inside the users list, so you can view their information.
         **/
        public function peek() {
            var_dump($this->_users);
        }

        protected function ready_array($username, $password, $email, $location = 'index.html', $access = false) {
            return array('USERNAME' => $username, 'PASSWORD' => $password, 'EMAIL' => $email, 'LOCATION' => $location);
        }


        public function add($username, $password, $email, $location = 'index.html') {
            $add = $this->ready_array($username, $password, $email, $location);
            $this->_users[] = $add;
        }

        public static function logout() {
            if (isset($_SESSION['LOGGED_IN'])) {
        if (session_destroy()) 
                    header('Location: index.html');
            }
        }

        /**
         * This method increments or returns login attempts.
         * @param <bool> true to increment by 1 and false to return.
         */
        public static function attempts($add = false) {
            if ($add === true)
                $_SESSION['LOGIN_ATTEMPTS'] += 1;
            else
                return $_SESSION['LOGIN_ATTEMPTS'];
        }

        public function site_name() {
            return self::$_script_name;
        }

        public function validate($un, $pw) {
            # Check all of the arrays for the user
            for ($i=0;$i<count($this->_users);$i++) {
                if (array_key_exists('USERNAME', $this->_users[$i])) {
            if ($this->_users[$i]['USERNAME'] == $un) {
                # We have found the user check to see if there password matches also.
                $info = $this->_users[$i];
                if ($info['USERNAME'] == $un && $info['PASSWORD'] == $pw) {
                    # We have a match redirect the user.
                    $_SESSION['LOGGED_IN'] = TRUE;
                    $_SESSION['LOGIN_ATTEMPTS'] = 0;
                    $_SESSION['USERNAME'] = $info['USERNAME'];
                    $_SESSION['EMAIL'] = $info['EMAIL'];
                    header('Location: ' . $info['LOCATION']);
                    return;
                }
            }
                }
            }
            echo '<h2 class=\'error\'>Incorrect username and or password, try again!</h2>';
            self::attempts(true);
        }

        /**
         * Forgot password? not a problem call this method with the correct username
         * and the user will be sent a password reminder. Please note that not of these passwords
         * are hashed meaning this is not a good idea to store personal information behind this script!
         * @param <string> The users email address.
         * @return <bool> Returns true upon success. 
         */
        public function forgot($email) {
            for ($i=0;$i<count($this->_users);$i++) {
                if (array_key_exists('EMAIL', $this->_users[$i])) {
                    if ($this->_users[$i]['EMAIL'] == $email)
                        $info = $this->_users[$i];
                } else return false;
            }
    if (isset($info) && is_array($info)) {
        # Send the user their password
        $to = $info['EMAIL'];
        $subject = 'You recently forgot your password | ' . self::$_script_name;
        $message = 'Hi ' . $info['USERNAME'] . ', ' . "\n\n";
        $message .= 'You recently requested your password for ' . self::$_script_name . ' if you didn\'t not to worry just ignore this ';
        $message .= 'email. Anyway you can find your email below, should you require anymore assistance then please contact us ';
        $message .= 'at ' . self::$_admin_email . ".\n\n";
        $message .= 'Username: ' . $info['USERNAME'] . "\n";
        $message .= 'Password: ' . $info['PASSWORD'];
        $message .= "\n\n" . 'Best Regards, ' . "\n" . self::$_admin_name;
        $headers = 'From: ' . self::$_admin_email . "\r\n" .
            'Reply-To: ' . self::$_admin_email . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

                # Uncomment for final version
                if (mail($to, $subject, $message, $headers)) return true;
            }
        }

        /**
         * The secure method, simply call this to lock any page down it's as simple as that.
         * @param <string> Name of the script EG: John's Script
         * @param <string> Email of the administrator EG: [email protected]
         * @param <string> Admin name EG: John Crossley
         * @return <object> Returns an instanciated object of this class.
         */
        public static function secure($s_name = '', $a_email = '', $a_name = '') {

            self::$_script_name = $s_name;
            self::$_admin_email = $a_email;
            self::$_admin_name = $a_name;

            if (!self::$_init instanceof JC_fsl) {
                self::$_init = new JC_fsl();
            }
            return self::$_init;
        }
    }

    # You may edit me
    $secure = JC_fsl::secure();

    ##########################################################################
    ########################## YOUR EDITING BLOCK ###########################

    $secure->add('mbhaynes', 'mbhaynes13', '[email protected]', 'mbhaynes.php');
    $secure->add('emory', 'emory13', '[email protected]', 'emory.php');
    $secure->add('ehg', 'ehg13', '[email protected]', 'redirect.html');
    $secure->add('dhgriffin', 'dhgriffin13', '[email protected]', 'dhgriffin.php');
    $secure->add('neo', 'neo13', '[email protected]', 'neo.php');
    $secure->add('first', 'first13', '[email protected]', 'first.php');
    $secure->add('test', 'test', '[email protected]', 'test.php');

    ##########################################################################
    ##########################################################################


    ############ FORM PROCESSING ############
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $secure->validate($_POST['username'], $_POST['password']);
    }
    if (isset($_GET['logout'])) $secure->logout();

    if (isset($_POST['forgot_password_button']) && isset($_POST['email'])) {
        // We need to send the user their password.
        if ($secure->forgot($_POST['email'])) {
            echo '<h2 class=\'success\'>Your password has been sent to your email address!</h2>';
        } else {
            echo '<h2 class=\'error\'>I\'m sorry but that email address has no record on this site.</h2>';
        }
    }

    ?>
    <?php if(!isset($_SESSION['LOGGED_IN'])): ?>
        <style type='text/css'>
            #fslv2-main{
        font-family:HelveticaNeue-Light, "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-weight:300;font-size:14px;line-height:1.6;
        margin-left:auto;
        margin-right:auto;
        width: 300px;
        padding: 10px 10px 10px 10px;
            }
            fieldset { border: none; margin: 0; padding: 0;}
            .fslv2 .input { 
        border: 1px solid #b9b9b9; 
        padding: 5px;
        width: 225px;
        outline: none;
        font-size: 13px;
            }
            .fslv2 label {
        float: left;
        width: 72px;
        line-height: 28px;
            }
            h3 { font-weight: normal; }
            a { color: #4a6a81; text-decoration: none; }
            a:hover { color: #4a6a81; text-decoration: underline; }
            .button {
        border: 1px solid #233d4f;
        border-bottom: 1px solid #233d4f;
        background-color: #4a6a81;
        border-radius: 2px;
        padding: 6px 5px;
        color: #ffffff;
        text-shadow: 0 1px rgba(0, 0, 0, 0.1);
        margin-left:auto;
        margin-right:auto;
        top: 5px;
        width: 100px;
        min-width: 100px;
        cursor: pointer;
        font-size: 13px;
        box-shadow: rgba(0,0,0,0.2);
        -webkit-box-shadow: rgba(0,0,0,0.2);
        -moz-box-shadow: rgba(0,0,0,0.2);
            }
            .input:focus {
        -moz-box-shadow: inset 0 0 3px #bbb;
        -webkit-box-shadow: inset 0 0 3px #bbb;
        box-shadow: inner 0 0 3px #bbb;
            }
            .fsl p.la { text-align: center; }
            .success {
        margin: 2em auto 1em auto;
        border: 1px solid #337f09;
        padding: 5px;
        background-color: #dd4b39;
        width: 400px;
        text-align: center;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        font-weight: normal;
        font-family:HelveticaNeue-Light, "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-weight:300;font-size:14px;line-height:1.6;
            }
            .error {
        margin: 2em auto 1em auto;
        border: 1px solid #233d4f;
        padding: 5px;
        background-color: #8bafc5;
        width: 400px;
        text-align: center;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
        border-radius: 5px;
        font-weight: normal;
        font-family:HelveticaNeue-Light, "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-weight:300;font-size:14px;line-height:1.6;
            }
        </style>
        <div id="fslv2-main">
        <?php if($secure->attempts() > 5): ?>
            <!-- Show the login form -->
            <p>Too many failed attempts, please try again later.</p>
        <?php elseif(isset($_GET['forgot_password'])): ?>
            <fieldset class="fslv2">
            <form method="post" action="#">
                <p>
                    <label for='email'>Email: </label>
                    <input type='text' name='email' class='input'/>
                </p>
                <p><input type='submit' name='forgot_password_button' class='button' value='Send!' /></p>
            </form>
        </fieldset>
        <small><a href="index.html">Cancel</a></small>
        <?php else: ?>
        <fieldset class="fslv2">
        <legend><?php echo $secure->site_name(); ?></legend>
    <form method="post" action="#">
                <p>
                    <label for='username'>Username: </label>
                    <input type='text' name='username' class='input'/>
                </p>
                <p>
                    <label for='password'>Password: </label>
                    <input type='password' name='password' class='input'/>
                </p>
                <p><input type='submit' name='login' class='button' value='Login' /></p>
            </form>
        </fieldset>
        <?php endif; ?>
        </div><!-- #fslv2-main -->
    <?php exit(); endif; ?>
Garlinda answered 25/1, 2013 at 20:36 Comment(3)
May I ask what the point of session_regenerate_id(); is? I know what it does, but why would you need it?Hippy
And you have an if statement around the login block. That would turn off the login block if they are already logged in. <?php if(!isset($_SESSION['LOGGED_IN'])): ?>Hippy
As I stated, I am not well-versed in PHP. This script was actually not written by me.Garlinda
P
3

If you go back to the main page after logging In, Try refreshing the page, If the session was set correctly then after refreshing you will be logged-In automatically or It will show you logged-In state, Else there would be something destroying all the sessions in main-page? I would go with the first condition, cause that happened to me many times, Its better to show the logIn form at the same page where you want to display registered user only content and after logging-In quickly redirect them to the same page so all the sessions work fine and back button won't create the problem as you redirected them to the same page....

EDIT: It won't effect users having there separate page as whole logIn form will be changed by that users content after logging In.

Try this:

if(isset($_SESSION['LOGGED_IN'])){
   //User is logged-In check for existence of its name file,
  $user = $_SESSION["LOGGED_IN"]."php";
If(file_exists($user)){
 //User's named file exists now include it.
  include("yourfolder/$user");
}else{
 //He was loggedIn in but file wasn't found...
 echo"Sorry nothing for you :P";
 }
}else{
   //Show the logIn form
}
Pagination answered 25/1, 2013 at 21:40 Comment(3)
Which database you using SQL, MYSQL? tell me the tables or content you want to to pull from DB So I may help you better....Pagination
Well the PHP script that I'm using is very simple, and has no database. If I want to protect a page with the login I just add this code to the page: <?php require('JC_fsl.php'); ?> I have each user set to redirect to a certain page when they log in (john to john.php, tom to tom.php, ect.) But again, my only problem is setting up a redirect in the PHP code that checks to see if the user is logged in and, if so, sends them to their specific page.Garlinda
Okay, firstly If its for usage of few people I would recommend to use databases instead of files, If its for a big project then you must have to use the database or else It would be impossible for you to control the project, Try Databases.... Now solution to your prob: Look my answer, I edit it for you again :)Pagination
M
2

If they're already logged in, why not redirect them AWAY from login.php? They shouldn't need to access that page if they've already authenticated their account:

login.php

session_start();

//If the user is already logged in, they have no business being here.
if(isset($_SESSION['LOGGED_IN'])){
     header('Location: logged_in_homepage.php');
     exit;
}

//User isn't logged in. Process login.
Melchizedek answered 25/1, 2013 at 20:43 Comment(6)
This is what I was looking for. But each user would have a separate homepage that they would need to be directed to until they logged out. Is there a way to redirect them to the page they were directed to after logging in? So that when the Login tab was pressed, they would go directly to test.phpGarlinda
Then you can redirect them to that homepage if you're storing their user ID or their username in a session variable.Melchizedek
So it would be something like $_SESSION['LOCATION']?Garlinda
Nope. A user id or a username would be best. i.e. $_SESSION['user_id']. That way you can redirect them to a page such as header('Location: user.php?id=' . $_SESSION['user_id'])Melchizedek
Thank you very much for your reply, but I apologize, I'm still not following you. In the PHP script that I'm using would the specific user id's be 'USERNAME'? Is there a way to change the name of the redirected page to their username? For example if john submits the login form, then it would redirect him to john.php when reloading login.php. My coding knowledge barley extends past HTML/CSSGarlinda
If you want to use a file name just as john.php, I would suggest that you look into some of the tutorials for mod rewrite with apache. Creating a physical file for each user would be madness.Melchizedek
P
2

you can also do that by adding this code in your head tag

<script language="javascript" type="text/javascript"> window.history.forward(); </script>

it will prevent the user to get back.

Padilla answered 14/3, 2020 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.