如何在 PHP 中正确启动会话


How to Properly Start a Session in PHP?

我最近在学习有关如何为我的网站制作自定义CMS的教程。我目前正在制作后端,因此用户可以创建和编辑页面。本教程有点旧,因此各种函数已被弃用。我能够修复其中的大部分,除了"session_register();"函数。例如,我在很多网站上看到过,包括这个告诉我使用"$_SESSION['admin']=$username;"的网站。这对我不起作用,因为我将其应用于许多页面,每个页面都要求我重新输入信息。

以下是我正在使用的文件:

admin_check.php:

<?php
$error_msg="";
if ($_POST['username']){
$username=$_POST['username'];
$password=$_POST['password'];
// Simple hard coded values for the correct username and password
$admin="Admin";
$adminpass="Password";
//connect to mysql here if you store admin username and password in your database
//This would be the prefered method of storing the values instead of hard coding them here into the script
if(($username !=$admin)||($password != $adminpass)){
    $error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
} else{
    $_SESSION['admin']=$username;
    require_once "index.php";
    exit();
}
}
?>
<?php
if ($_SESSION['admin']!="Admin"){
echo '<div class="container" style="background-color: #FFF ;"><h3><i   class="glyphicon glyphicon-alert text-danger"></i> Solo los administradores
      tienen permiso para ver este directorio. No se admite gente con Lag!        </h3><br/>
      <!DOCTYPE html
<html>
<head>
    <title>Login Administrador</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">       
    <link href="../css/bootstrap.min.css" rel="stylesheet" />
    <link href="../css/styles.css" type="text/css" rel="stylesheet">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-    glyphicons.css" rel="stylesheet">
     </head>
      <body style="padding-top: 5px; background-color: #EEE ;">
    <div style="max-width: 450px; max-height: 550px; background-color: #CCC; padding-top: 30px; box-shadow: 0 0 15px #DDD; border-radius: 10px" class="container">
        <div class="jumbotron" style="background-color: #fff; max-height: 470px; padding: 10px; border-radius: 2; box-shadow: 0 0 12px #777;">
            <legend class="text-success">LOGIN ADMINISTRATOR</legend>
            <hr />                
            <p style="font-size: 12pt;">Please enter your username and password to login into the admin site.</p>
            <form action="admin_check.php" method="post" target="_self" class="form-group">
                <label class="label label-default">username</label>
                <input type="text" class="form-control" placeholder="username" name="username" id="username">
                <br/>                    
                <label class="label label-default">password</label>
                <input type="password" class="form-control" placeholder="password" name="password" id="password">
                <br/>
                <button class="btn-success" value="submit" type="submit" name="button" id="button" >Submit</button>
            </form><br/>
            '.$error_msg.'
        </div>
    </div>
</body>
</html>
<br/><br/>
         <center> <a href="../" >Click aquí para regresar a un lugar seguro.</a>    </div></center>';

    exit();
    }
    ?>

^ 如您所见,这是管理员输入用户名和密码的地方,我希望以某种方式存储用户名和密码,例如在cookie中,这样他们就可以自由导航,而无需一遍又一遍地输入用户名和密码。

索引.php:

<?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<body id="home">
    <div class="container" style="background-color: white;">
        <h2 style="color: #FF691F"><i class="fa fa-home fa-2x"></i> Home</h2>
    </div>
</body>        
<?php include "admin_footer.php"; ?>

create_blog.php:

 <?php
session_start();
include_once "admin_check.php";?>
<?php
include "admin_header.php";
?>
<script type="text/javascript">
function validate_form(){
    valid=true;
    if(document.form.pagetitle.value===""){
        alert("Please Enter a Page Title!");
        valid=false;
    }else if{
        alert("Please Enter Keywords about this Page!");
        valid=false;
    }
    return valid;
}
</script>
<script type="text/javascript">
function validate_form1(){
    valid=true;
    if(document.form.pid.value===""){
        alert("Please Enter a Page ID!");
        valid=false;
    }
    return valid;
}
</script>
<body id="blog">
<div class="container" style="background-color: white; box-shadow: 0 -5px 9px 3px #b2b2b2;">
    <br/>
    <h2 style="color: #777 ;"><i class="fa fa-book fa-lg"></i> Upload Blog Entry</h2>
    <p class="text-danger text-center">Title, Body, and Keywords are required to create new post! None should be left blank!</p>
    <a href="mmoAdmin/"><h6 class="text-muted pull-right"><< Back Home</h6>  </a>
    <br/>
    <form id="form1" name="form1" method="post" action="edit_blog.php" onsubmit="return validate_form1();" class="form-inline">
        <div class="form-group">
            <button class="btn-default" type="submit" name="button2" id="button2" value="Edit Post">Edit Post</button>
        </div>
        <input name="pid" type="text" id="pid" size="8" maxlength="11" class="form-control"/>
        <span id="helpBlock1" class="help-block">Enter the ID of the post you want to edit. eg: "blog/article.php?pid=<'this is the id'>"</span>
    </form>
    <br/>
    <form id="form2" name="form2" method="post" action="delete_blog.php" onsubmit="return validate_form2();" class="form-inline">
        <div class="form-group">
            <button class="btn-default" type="submit" id="button3" name="button3" value="Delete Post">Delete Post</button>
        </div>
        <div class="form-group"><input type="text" class="form-control" id="pid" name="pid"/></div>
        <span id="helpBlock2" class="help-block">Enter the ID of the post you want to delete. eg: "blog/article.php?pid=<'this is the id'>"</span>
    </form>
    <br/>
    <form id="form" name="form" method="post" action="congrat_blog.php" onsubmit="return validate_form();">
    <div class="form-group">
        <label>Title</label>
        <input type="text" name="pagetitle" id="pagetitle" class="form-control" placeholder="Title..." value="<?php echo $pagetitle; ?>"/>
        <br/>
        <br/>
        <label>Body</label>
        <textarea name="pagebody" id="pagebody" style="height: 480px; width: 100%" ><?php echo $pagebody; ?></textarea>
        <br/>
        <label>Keywords</label>
        <input type="text" name="keywords" id="keywords" class="form-control" placeholder="blog, mmob, etc..." value="<?php echo $keywords; ?>" />
        <br/>
        <button type="submit" class="btn-success" name="button" id="button"   value="Create this page now">Submit</button>
    </div>
    </form>
</div>
</body>

<?php include "admin_footer.php"; ?>

^像这样,我有多个页面,所有页面在文档开头都有php函数"session_start();",我included_once"admin_check.php"和"$_SESSION['admin']=$username"功能。

注意:admin_header.php和admin_footer.php只是HTML页眉导航栏和页脚,所以我不必为单个页面更正它们。

我对 php 相当陌生。我这样做的正确道路吗?基本上,我所尝试的只是一个登录功能,以便管理员可以访问后端,这将允许他们将信息上传到数据库中,因此它会填充站点。

以下是我一直在关注的教程系列的链接,以创建此基本CMS:

如何构建PHP和MySQL CMS网站软件

谢谢你的时间!

因此,该教程没有提到必须在每个页面中启动会话,但它确实如此。

因此,session_start();但使用会话成为所有文件的一部分。

错误报告会在这里对您有所帮助:http://php.net/manual/en/function.error-reporting.php

教程可能没有涵盖的另一件事是"密码"。

使用以下方法之一:

  • CRYPT_BLOWFISH
  • crypt()
  • bcrypt()
  • scrypt()
  • 在开墙上
  • PBKDF2
  • PBKDF2 on PHP.net
  • PHP 5.5 的password_hash()函数。
  • 兼容包(如果 PHP <5.5)https://github.com/ircmaxell/password_compat/

其他链接:

  • PBKDF2 for PHP

关于列长的重要旁注:

如果您决定使用 password_hash() 或兼容包(如果 PHP <5.5)https://github.com/ircmaxell/password_compat/,请务必注意,如果您当前密码列的长度小于 60,则需要将其更改为该长度(或更高)。手册建议长度为 255。

您需要更改列的长度并使用新的哈希重新开始才能使其生效。否则,MySQL 将以静默方式失败。

如果计划稍后使用数据库,请将 PDO 与预准备语句一起使用,或将 mysqli_* 与预准备语句一起使用

  • 这只是一个见解。

查看您的代码,您忘记了 PHP 文件开头的session_start(),最好将其放在 PHP 文件的顶部,以便会话正常工作。这通常设置(或使用已经传递的)cookie,然后识别用户$_SESSION以便变量起作用。

http://php.net/manual/en/function.session-start.php

问题:在代码中设置会话之前,您忘记启动会话。

溶液:将代码的第一部分替换为固定的:

<?php
session_start();
$error_msg="";
if ($_POST['username']){
    $username=$_POST['username'];
    $password=$_POST['password'];
    // Simple hard coded values for the correct username and password
    $admin="Admin";
    $adminpass="Password";
    //connect to mysql here if you store admin username and password in your database
    //This would be the prefered method of storing the values instead of hard coding them here into the script
    if(($username !=$admin)||($password != $adminpass)){
        $error_msg='<h3 class="text-danger">Login information incorrect, please try again.</h3>';
    } else{
        $_SESSION['admin']=$username;
        require_once "index.php";
        exit();
    }
}
?>

注意:请记住在尝试访问$_SESSION数组或尝试设置数组之前,以及在将任何输出发送到浏览器之前,在页面上运行session_start()语句。

参考网址 :

http://php.net/manual/en/session.examples.basic.php