php – 这段代码安全吗?

前端之家收集整理的这篇文章主要介绍了php – 这段代码安全吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<?PHP
session_start();

include("connect.PHP");

$timeout = 60 * 30;
$fingerprint = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);

if(isset($_POST['userName']))
{
    $user = MysqL_real_escape_string($_POST['userName']);
    $password = MysqL_real_escape_string($_POST['password']);
    $matchingUser = MysqL_query("SELECT * FROM `users` WHERE username='$user' AND password=MD5('$password') LIMIT 1");
    if (MysqL_num_rows($matchingUser))
    {
        if($matchingUser['inactive'] == 1)//Checks if the inactive field of the user is set to one
        {
            $error = "Your e-mail Id has not been verified. Check your mail to verify your e-mail Id. However you'll be logged in to site with less privileges.";
            $_SESSION['inactive'] = true;
        }
        $_SESSION['user'] = $user;
        $_SESSION['lastActive'] = time();
        $_SESSION['fingerprint'] = $fingerprint;
    }
    else
    {
        $error = "Invalid user id";
    }
}
if ((isset($_SESSION['lastActive']) && $_SESSION['lastActive']<(time()-$timeout)) || (isset($_SESSION['fingerprint']) && $_SESSION['fingerprint']!=$fingerprint)
     || isset($_GET['logout'])
    )
{
    setcookie(session_name(),'',time()-3600,'/');
    session_destroy();
}
else
{
    session_regenerate_id(); 
    $_SESSION['lastActive'] = time();
    $_SESSION['fingerprint'] = $fingerprint;
}
?>

这只是http://en.wikibooks.org/wiki/PHP_Programming/User_login_systems修改版本

什么是setcookie(session_name(),”,time() – 3600,’/’);在这做?

这是一个错误
我使用这个登录表单:

<?PHP 
   if(!isset($_SESSION['user']))
    {
        if(isset($error)) echo $error;
           echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
        <label>Username: </label>
        <input type="text" name="userName" value="';if(isset($_POST['userName'])) echo $_POST["userName"]; echo '" /><br />
        <label>Password: </label>
        <input type="password" name="password" />
        <input type="submit" value="Login" class="button" />
        <ul class="sidemenu">
        <li><a href="register.PHP">Register</a></li>
        <li><a href="forgotPassword.PHP">Forgot Password</a></li>
    </ul>
    </form>';
    }
    else
    {
        echo '<ul class="sidemenu">
        <li>' . $_SESSION['user'] . '</li>
        <li><a href="' . $_SERVER["PHP_SELF"] . '?logout=true">logout</a></li>
        </ul>';
    }
?>

错误是当我注销时,页面保持不变,即登录表单不显示显示相同的注销和用户.当我刷新页面时,它变得正常.

当您注销时,首先,您正在排队cookie的破坏(它将在发送响应后发生),然后在呈现您的页面之后立即排队.浏览器在渲染之前没有机会删除cookie,并且$_SESSION变量仍然存在.

关于session_destroy的PHP文档说:

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session,or unset the session cookie.

一个解决方案是,而不是破坏会话和cookie,只需取消设置将导致身份验证的变量:

unset($_SESSION['user']);
unset($_SESSION['lastActive']);
unset($_SESSION['fingerprint']);

请注意:我建议将代码拆分为函数.这将使它更有条理和可读(如果你做对了就可以重复使用).

猜你在找的PHP相关文章