PHP会话登录和注销


PHP sessions logging in and logging out

我必须制作一个简单的网站,你可以登录和退出,如果用户登录了,他们会看到一些功能,否则他们不会看到。我不太擅长网络开发,但我已经设法找到了一些似乎奏效的东西。我决定在登录和注销时不想将用户重定向到另一个页面,所以这让我有点难以理解。

我只是想知道我是否会以正确的方式开始和结束这场比赛,如果可能的话,是否有人能给我一些建议,让比赛变得更好。

<?php

if(isset($_POST['logout'])) {
    session_destroy();
    }
}
    session_start();
if(!isset($_SESSION['username'])) {
    if (!empty($_POST['username']) && !empty($_POST['password'])) {
        $result = mysql_query("SELECT * FROM users WHERE username ='$_POST['username']' AND password = '$_POST['password']'");
        if(mysql_num_rows($result)) 
            $_SESSION['username'] = $_POST['username'];
        }
        else {
            echo "";
        }
    }
}
?>
        <?php if(!isset($_SESSION['username'])) {
                echo '<div id = "account">
                        <form name="input" action="index.php" method="post">
                            Username:<input type="text" name="username" /> Password:<input type="password" name="password" />
                            <input type="submit" value="GO!" />
                        </form>
            }
            else {
                    echo "Signed in"
                    <form name='logout' action='index.php' method='post'>
                    <input type='submit'value='Reset' name='logout'/>
                    ";
            } ?> 
            <?php
            $test = mysql_query("SELECT * FROM posts ORDER BY post_id DESC");
            if($test) { 
                while($row = mysql_fetch_array($test)) { 
                    echo '<div class="posts">';
                        echo "$row[post]"; 
                    echo '</div>';
                }
            }

我对您的代码进行了修改。我试着添加了很多评论,让它更容易理解。希望没有语法错误,但我实际上无法测试,因为我没有MySQL数据库之类的。

这是你的主要代码:

<?php
//When you are developing and testing, set the error level as high as possible.
//This will help you find problems early. A well written program will have no errors and warnings, ever.
error_reporting(E_ALL | E_STRICT);
//Starting the session should be one of the first things your code does, and should only be done once.
session_start();
require 'config.php';
if(isset($_POST['logout']))
{
    //I don't think there is any reason to check if username is set. If you are logging out, just destroy.
    session_destroy();
    //Also unset the session username since session_destroy() does not affect existing globals.
    unset($_SESSION['username']);
}
//I changed this to elseif, because there should not be a condition where you are logging out and checking for a login.
elseif(!isset($_SESSION['username']))
{
    //You should not assume that variables are set, because accessing them if they are not set
    //will cause a warning. I've added isset().
    if(isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password']))
    {
        //You absolutely MUST escape your strings or you are at risk of SQL injection.
        //Use mysql_real_escape_string() for this.
        $username = mysql_real_escape_string($_POST['username']);
        $password = mysql_real_escape_string($_POST['password']);
        $result = mysql_query("SELECT * FROM members WHERE username ='$username' AND password = '$password'");
        //You should probably check that the value === 1 here.
        //I'm assuming it should always be 1 or 0.
        if(0 === mysql_num_rows($result))
        {
            $_SESSION['username'] = $username;
        }
        else {
            echo "Fail :(";
        }
    }
    //If you put an else statement here, you could print an error for if the username was not specified.
}
//You should not have SQL queries in your template, so I moved this here.
//Notice that I'm just setting $posts to the data. It's best to just pass
//the data, and format it in the template.
$result = mysql_query("SELECT * FROM posts ORDER BY post_id DESC");
if($result)
{
    $posts = array();
    while($row = mysql_fetch_array($result))
    {
        $posts[] = $row['post'];
    }
}
else
{
    $posts = false;
}
//Try to separate code logic from templates.
//Your program is small, so it's not that important, but I would do it anyway.
require 'template.php';
?>

这是您的模板代码,应该放在一个名为template.php的新文件中:

<div id = "container">
    <h1>#HookyGear Bay</h1>
    <div id = "login">
        <?php if(!isset($_SESSION['username'])) {
                echo '<div id = "accountBox">
                        <form name="input" action="index.php" method="post">
                            Username:<input type="text" name="username" /> Password:<input type="password" name="password" />
                            <input type="submit" value="Sign In" />
                        </form>
                </div>';
            }
            else {
                    echo "<div id='accountBox'>You Are logged in as ".$_SESSION['username']."
                    <form name='logout' action='index.php' method='post'>
                    <input type='submit'value='Reset' name='logout'/>
                    </div> ";
            } ?> 
    </div>
        <div id = "content">
            <?php
            if(false !== $posts)
            {
                foreach($posts as $post)
                {
                    echo '<div class="blogPosts">'.$post.'</div>';
                }
            }
            else { ?> 
                <div class="blogPosts"><?php echo "no blog posts"; ?></div> 
            <?php
            }
            ?>
            <div style="clear:both;"></div>
        </div>
</div>

您可以将用户重定向到不同的注销特定页面,而不是每次加载页面时都检查$_POST['logout']。

您可以尝试调用session中的方法。就像我的

在这里,它会检查你是否连接到你的数据库,我将其命名为connect.inc.php

<?php
if(!mysql_connect('localhost', 'root', '')|| !mysql_select_db('byp_db'))
{
die(mysql_error());
}
?>

接下来,我创建了我的core.inc.php,它将检查你是否已经在session中,你将在中使用loggedin()方法

<?php
error_reporting(E_ALL ^ E_NOTICE); 
ob_start();
session_start();
$current_file = $_SERVER['SCRIPT_NAME'];
$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin() {
      if(isset($_SESSION['user_p_info_id'])&&!empty($_SESSION['user_p_info_id'])) {
    return true;
}else {
    return false;
}
}
function getuserfield($field){
$query = "SELECT `$field` FROM `user_p_info` where `user_p_info_id`='".$_SESSION['user_p_info_id']."'";
if($query_run = mysql_query($query)){
    if($query_result = mysql_result($query_run, 0, $field)){
        return $query_result;
    }
}
}
?>

下一步,你将创建你的日志形式

<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(isset($_POST['uname']) && isset($_POST['password'])){
$uname = $_POST['uname'];
$pword = $_POST['password'];
//echo $uname;
//echo $pword;
if(!empty($uname)&&!empty($pword)){
$query_login = "SELECT * FROM user_a_info where username = '$uname' and password = '$pword'";
//echo $query_login;
$query_result = mysql_query($query_login);
$num_rows = mysql_num_rows($query_result);  
    if($num_rows == 0){
?>
<script type="text/javascript"> 
alert("Invalid Data !");  
</script>

<?php                   
    }else{
        //echo "validated";
        $user_p_info_id = mysql_result($query_result, 0, 'user_p_info_id');
        $_SESSION['user_p_info_id']=$user_p_info_id;
        header('Location: index.php');

}
} 
}
?>
<form action="login.php" method="POST">
<p> USERNAME : <input type="text" name="uname" /> </p>
<p> PASSWORD : <input type="password" name="password" /> </p>
<p> <input type="submit" value="LOGIN" /> </p>
</form>

然后你的注销功能会像这个

<?php
require 'core.inc.php';
session_destroy();
header('Location: ../index.php');
?>

只需注意,如果你想检查你是否在session中,只需将此条件设置为

<?php
require 'connections/connect.inc.php';
require 'connections/core.inc.php';
if(loggedin()) {
// Do something
}
?>

希望这能帮助