开发者

PHP Session Management - Basics

i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....

what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...

can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some 开发者_如何学Ctutorial...

p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner


First check out wheather session module is enabled

<?php
    phpinfo();
?>

Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.

First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.

session_start();
$_SESSION['username'] = 'alex';

Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.

session_start();
echo "User : ".$_SESSION['username'];

To check whether a session variable exists or not you can use the isset() function.

session_start();
   if (isset($_SESSION['username'])){
      echo "User : ".$_SESSION['username'];
   } else {
      echo "Set the username";
      $_SESSION['username'] = 'alex';
   }


  • Every pages should start immediately with session_start()
  • Display a login form on your public pages with minimum login credentials (username/password, email/password)
  • On submit check submitted data against your database (Is this username exists? » Is this password valid?)
  • If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
  • Check for this variable on every reserved page like:

    <?php
    if(!isset($_SESSION['user_id'])){
    //display login form here
    }else{
    //everything fine, display secret content here
    }
    ?>
    


Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-

<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>

In the login page, where you are writing the login process logic, use the following code:-

<?php
if (isset($_POST['btn_submit'])) {
    $sql = mysql_query("SELECT userid, email, password FROM table_users
                        WHERE username = '".mysql_real_escape_string($_POST['username'])."'
                        AND is_active = 1");

    if (mysql_num_rows($sql) == 1) {
        $rowVal = mysql_fetch_assoc($sql);

        // Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
        if (md5($_POST['password']) == $rowVal['password']) {
            $_SESSION['username'] = $_POST['username'];
            $_SESSION['email'] = $rowVal['email'];
            $_SESSION['userid'] = $rowVal['userid'];
        }
    }
}
?>

Now in all the reserved pages, you need to do two things:-

  • First, initialize / start the session, as mentioned at the top.
  • Initialize all the important configuration variables, as required by your web application.
  • Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.

The definition of the user-defined function "checkUserStatus()" will be somewhat like:-

function checkUserStatus() {
    if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
        return true;
    }
    else {
        header("Location: http://your_website_domain_name/login.php");
        exit();
    }
}

Hope it helps.


It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.

Simplest solution would be to use some framework like Kohana which has built-in support for such function.

To make it yourself you should use some mechanisme like this:

session_start();
if (isset($_SESSION['auth_key'])) {
    // TODO: Check in DB that auth_key is valid
    if ($auth_key_in_db_and_valid) {
         // Okay: Display page!
    } else {
         header('Location: /login/'); // Or some page showing session expired
    }
} else {
    header('Location: /login/'); // You're login page URL
    exit;
}

In the login page form:

session_start();
if (isset($_POST['submit'])) {
    // TODO: Check username and password posted; consider MD5()
    if ($_POST['username'] == $username && $_POST['password'] == $password) {
        // Generate unique ID.
        $_SESSION['auth_key'] = rand();
        // TODO: Save $_SESSION['auth_key'] in the DB.
        // Return to some page
        header('Location: ....');
    } else {
        // Display: invalid user/password
    }
}

Missing part: You should invalidate any other auth_key not used after a certain time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜