php 使用 slim+twig 的会话,扩展另一个模板的模板不能有正文

php sessions with slim+twig, A template that extends another one cannot have a body

我正在制作一个带有 twig 和 slim 的网站,运行 在尝试设置用户身份验证系统时遇到了一些问题。

我正在使用标准 LAMP 配置(mysql、php5、apache2),以及 composer、twig 和 slim。

我通读了 this 教程并认为我会做类似的事情,但不知道如何将其实施到我的应用程序中。我遇到的问题是 php sessions 部分。到目前为止,我只将 phpPDO 用于我的数据库连接(我使用 AJAX 对我的 .php 文件进行了 POST 调用),但现在看来我实际上需要将 php 代码插入到我的 twig 文件中。

所以我尝试这样做:

{% extends 'main.twig' %}

<?php
/*** begin our session ***/
session_start();
/*** set a form token ***/
$form_token = md5( uniqid('auth', true) );
/*** set the session form token ***/
$_SESSION['form_token'] = $form_token;
?>

{% block title %}
Sign Up | PTC Testers
{% endblock title %}

{% block stylesheet %}
<link rel="stylesheet" type="text/css" href="css/login.css">
{% endblock stylesheet %}

{% block content %}
<h1>Sign Up</h1>
    <form method="post">
        <fieldset>
            <p>
                <label for="email">Email</label>
                <input type="text" name="email" value="" maxlength="40" placeholder="john@example.com">
            </p>
            <p>
                <label for="password">Password</label>
                <input type="text" name="password" value="" maxlength="20" />
            </p>
            <p>
                <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
                <input type="submit" value="&rarr; Login" />
            </p>
        </fieldset>
    </form>
{% endblock content %}

并得到以下错误:A template that extends another one cannot have a body in "signup.twig" at line 2.

因为这是我第一次做这样的事情,所以我不知道如何进行,也不知道正确的方法是什么。欢迎任何意见。

如果您需要有关我的应用程序、配置等的更多信息,here's a github repository of the project。相关文件位于 db_queriestemplates 和根文件夹 (index.php)。

感谢您的帮助

来自the Slim documentation

A Slim application does not presume anything about sessions. If you prefer to use a PHP session, you must configure and start a native PHP session with session_start() before you instantiate the Slim application.

此外,不要放入不可能的模板,您真正需要的是 middleware.

这意味着在 index.php 中,您的代码将类似于:

/*** begin our session ***/
session_start();

$app = new \Slim\Slim(array(
    'view' => new \Slim\Views\Twig()
));

$csrfTokenGenerator = function () {
    $form_token = md5( uniqid('auth', true) );

    $_SESSION['form_token'] = $form_token;
};

$app->get('/login', $csrfTokenGenerator, function() use ($app) {
    $app->render('login.twig');
})->name('login');

也就是说,Slim 已经作为单独的软件包为您提供了此功能 - Slim-Csrf - 值得一试。