php登录系统适用于不同类型的用户

时间:2015-04-27 18:34:00

标签: php html mysqli

我有一个有效的登录系统,可以检查每个页面是否登录用户。我还添加了一个列“usertype”,其中0表示学生,1表示教授,2表示头部,3表示工作人员。当我试图检查用户组是1还是2等...它不起作用时,即使我在数据库中的帐户设置为1,也不会在页面中显示任何内容。如果有人帮我查找什么是错的,这将是伟大的!提前谢谢。

这是我的覆盖页面:

    <?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$user = $_SESSION['username']
?>
<!DOCTYPE html>
<html>

 <?php if (login_check($mysqli) == true) : ?>
            <p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
          <?php   if ($_SESSION['usertype'] == 1) { ?>

<form method="post" action="dboverride.php" name="OverrideForm" id="OverrideForm" autocomplete="off">
    <fieldset>
        <legend><b>Personal Details</b></legend>
        <div>
            <label for="name" accesskey="N">First Name</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$name = $mysqli->query("SELECT name FROM student WHERE username = '$user'")->fetch_object()->name;  
print_r($name);
?>
        </div>
<br>
        <div>
            <label for="mname" accesskey="M">Mid. Name</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$mname = $mysqli->query("SELECT mname FROM student WHERE username = '$user'")->fetch_object()->mname;  
print_r($mname);
?>
        </div>
<br>
        <div>
            <label for="fname" accesskey="F">Last Name</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$fname = $mysqli->query("SELECT fname FROM student WHERE username = '$user'")->fetch_object()->fname;  
print_r($fname);
?>
        </div>
<br>
        <div>
            <label for="sid" accesskey="i">Student ID</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$sid = $mysqli->query("SELECT sid FROM student WHERE username = '$user'")->fetch_object()->sid;  
print_r($sid);
?>
        </div>
<br>
<div>
            <label for="email" accesskey="E">Email</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$email = $mysqli->query("SELECT email FROM student WHERE username = '$user'")->fetch_object()->email;  
print_r($email);
?>
        </div>
<br>
        <div>
            <label for="phone" accesskey="p">Phone No.</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$phone = $mysqli->query("SELECT phone FROM student WHERE username = '$user'")->fetch_object()->phone;  
print_r($phone);
?>
        </div>
<br>
<div>
    <label for="sc" accesskey="s">Scolarship</label>&nbsp;&nbsp;&nbsp;&nbsp;
<?php
$mysqli  = new Mysqli($servername, $username, $password, $dbname) or die(mysql_error());
$Scolarship = $mysqli->query("SELECT Scolarship FROM student WHERE username = '$user'")->fetch_object()->Scolarship;  
print_r($Scolarship);
?>

</div>    

   </fieldset>
<br >

    <fieldset>
        <legend><b>Subject Details</b></legend>

<div>
            <label for="class" accesskey="c">Subject</label>&nbsp;&nbsp;
            <input name="class" type="text" id="class" size="50" required />
        </div>
<br>    
        <div>
            <label for="section" accesskey="o">Section</label>&nbsp;&nbsp;
            <input name="section" type="number" id="section" min="1" max="9" required />
        </div>
<br>    

        <div>
            <label for="semester" accesskey="S">Semester</label>
            <select name="semester" id="semester" required="required">
                <option value="F15">Fall 2015</option>
                <option value="S15">Summer 2015</option>
                <option value="SP16">Spring 2016</option>
            </select>
        </div>
    </fieldset>
<br >
    <fieldset>
        <legend><b>Agreement</b></legend>
<form action="#" onSubmit="if(document.getElementById('agree').checked) { return true; } else { alert('Please indicate that you have agreed on the terms'); return false; }">

<input type="checkbox" name="checkbox" value="check" id="agree" required />&nbsp;By checking this box, i am fully responsible for the data entered above. I am also providing my official online signature to be liable in however the site may use it for.
<br> <i><font size="2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;* Date and time are recorded for various reasons.</font></i>

<br><br>
            <label for="date" accesskey="c">&nbsp;&nbsp&nbsp;&nbsp;&nbsp;Current Date & Time : </label>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
<script type="text/javascript">
document.write ('<span id="date-time">', new Date().toLocaleString(), '<\/span>')
if (document.getElementById) onload = function () {
    setInterval ("document.getElementById ('date-time').firstChild.data = new Date().toLocaleString()", 50)
}
</script>
    </fieldset>
<br>
    <input type="submit" class="submit" id="submit" value="Submit" />&nbsp;&nbsp;&nbsp;<input type="reset" value="Reset"><br>
</form>
</form>
<?php
}
?>
        <?php else : ?>
            <p>
                <span class="error">You are not authorized to access this page.</span> Please <a href="index.php">login</a>.
            </p>
        <?php endif; ?>
</html>

my functions.php:

    <?php
include_once 'psl-config.php';

function sec_session_start() {
    $session_name = 'sec_session_id';   // Set a custom session name
    $secure = SECURE;
    // This stops JavaScript being able to access the session id.
    $httponly = true;
    // Forces sessions to only use cookies.
    if (ini_set('session.use_only_cookies', 1) === FALSE) {
        header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
        exit();
    }
    // Gets current cookies params.
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams["lifetime"],
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure,
        $httponly);
    // Sets the session name to the one set above.
    session_name($session_name);
    session_start();            // Start the PHP session 
    session_regenerate_id(true);    // regenerated the session, delete the old one. 
}
function login($email, $password, $mysqli) {
    // Using prepared statements means that SQL injection is not possible. 
    if ($stmt = $mysqli->prepare("SELECT id, username, password, salt 
        FROM student
       WHERE email = ?
        LIMIT 1")) {
        $stmt->bind_param('s', $email);  // Bind "$email" to parameter.
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($user_id, $username, $db_password, $salt);
        $stmt->fetch();

        // hash the password with the unique salt.
        $password = hash('sha512', $password . $salt);
        if ($stmt->num_rows == 1) {
            // If the user exists we check if the account is locked
            // from too many login attempts 

            if (checkbrute($user_id, $mysqli) == true) {
                // Account is locked 
                // Send an email to user saying their account is locked
                return false;
            } else {
                // Check if the password in the database matches
                // the password the user submitted.
                if ($db_password == $password) {
                    // Password is correct!
                    // Get the user-agent string of the user.
                    $user_browser = $_SERVER['HTTP_USER_AGENT'];
                    // XSS protection as we might print this value
                    $user_id = preg_replace("/[^0-9]+/", "", $user_id);
                    $_SESSION['user_id'] = $user_id;
                    // XSS protection as we might print this value
                    $username = preg_replace("/[^a-zA-Z0-9_\-]+/", 
                                                                "", 
                                                                $username);
                    $_SESSION['username'] = $username;
                    $_SESSION['login_string'] = hash('sha512', 
                              $password . $user_browser);
                    // Login successful.
                    return true;
                } else {
                    // Password is not correct
                    // We record this attempt in the database
                    $now = time();
                    $mysqli->query("INSERT INTO login_attempts(user_id, time)
                                    VALUES ('$user_id', '$now')");
                    return false;
                }
            }
        } else {
            // No user exists.
            return false;
        }
    }
}

function checkbrute($user_id, $mysqli) {
    // Get timestamp of current time 
    $now = time();

    // All login attempts are counted from the past 2 hours. 
    $valid_attempts = $now - (2 * 60 * 60);

    if ($stmt = $mysqli->prepare("SELECT time 
                             FROM login_attempts 
                             WHERE user_id = ? 
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query. 
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins 
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}

function login_check($mysqli) {
    // Check if all session variables are set 
    if (isset($_SESSION['user_id'], 
                        $_SESSION['username'], 
                        $_SESSION['login_string'])) {

        $user_id = $_SESSION['user_id'];
        $login_string = $_SESSION['login_string'];
        $username = $_SESSION['username'];

        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password 
                                      FROM student
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter. 
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();
                $login_check = hash('sha512', $password . $user_browser);

                if ($login_check == $login_string) {
                    // Logged In!!!! 
                    return true;
                } else {
                    // Not logged in 
                    return false;
                }
            } else {
                // Not logged in 
                return false;
            }
        } else {
            // Not logged in 
            return false;
        }
    } else {
        // Not logged in 
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&amp;', '&#038;', $url);
    $url = str_replace("'", '&#039;', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

0 个答案:

没有答案