在Slim应用程序中实现标准PHP表单验证

时间:2018-10-03 13:32:20

标签: php forms validation twig slim

因此,我正在尝试为注册表单实施php服务器端验证。我正在使用苗条的框架以及树枝模板来显示html。我一直在尝试使用this example来实现这一目标,但我认为我设置瘦路由的方式会干扰在注册表单上正确显示的错误消息。

我的应用程序当前的工作方式是用户导航到显示注册表的注册表页面。如图所示:

$app->get('/register', function(Request $request, Response $response)
{
    return $this->view->render($response,
        'register.html.twig',
        [
            'css_path' => CSS_PATH,
            'landing_page' => $_SERVER["SCRIPT_NAME"],
            'action_register' =>  './register/success',
            //'initial_input_box_value' => null,
            'page_title' => 'Login App - Register',
        ]);
})->setName('register');

'action_register' => './register/success',代表html树枝表单中的表单“ action”属性,并指示在何处以及如何处理表单数据以及对提交表单的响应。可以在此处看到:(请注意,注册/成功页面的前几行是我一直在用于PHP验证的指南中使用的示例)

$app->post('/register/success', function(Request $request, Response $response) use ($app)
{
    $nameError = " "; 

    if(isset($_POST['submit']))
    {
        if (empty($_POST["username"])) {
            $nameError = "Name is required";
        } else {
            $name = test_input($_POST["username"]);
// check name only contains letters and whitespace
            if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                $nameError = "Only letters and white space allowed";
            }
        }
    }

    function test_input($data)
    {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }

    $arr_tainted_params = $request->getParsedBody();

    $sanitizer_validator = $this->get('validate_sanitize');
    $password_hasher = $this->get('hash_password');

    $tainted_email = $arr_tainted_params['email'];
    $tainted_username = $arr_tainted_params['username'];
    $tainted_password = $arr_tainted_params['password'];

    $model = $this->get('model');
    $sql_wrapper = $this->get('sql_wrapper');
    $sql_queries = $this->get('sql_queries');
    $db_handle = $this->get('dbase');

    $cleaned_email = $sanitizer_validator->validate_email($tainted_email);
    $cleaned_username = $sanitizer_validator->validate_username($tainted_username);
    $cleaned_password  = $sanitizer_validator->validate_password($tainted_password);
    $hashed_cleaned_password = $password_hasher->hash_password($cleaned_password);

    $model->set_user_values($cleaned_username, $cleaned_email, $hashed_cleaned_password);
    $model->set_sql_wrapper($sql_wrapper);
    $model->set_sql_queries($sql_queries);
    $model->set_db_handle($db_handle);

    if ($sanitizer_validator->get_validate_messages() == ' ')
    {
        $model->store_user_details();

        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $cleaned_username;

        $arr_storage_result_message = '';

        echo $sanitizer_validator->get_validate_messages(); //this will be turned into a proper alert prompt at a later date
    }

    if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true)
    {
        return $this->view->render($response,
            'display_user.html.twig',
            [
                'css_path' => CSS_PATH,
                'landing_page' => $_SERVER["SCRIPT_NAME"],
                //'action_register' => 'index.php/register',
                //'initial_input_box_value' => null,
                'page_title' => 'Login App - Display',
                'username' => $cleaned_username,
                'hashed_password' => $cleaned_password,
            ]);
    }
});

想法是,用户创建一个帐户,然后登录,从而显示“ display_user.html.twig”。否则,有关表格验证的错误消息应显示在注册表格本身上。但是,注册表仅显示在/ register页面上。但是注册表格会将数据发布并在注册/成功页面上进行处理。

因此,我不确定php验证指南的代码是否放置在错误的位置,或者我的瘦路由对于表单验证而言是否不正确。我认为问题在于,提交表单后会将用户重定向到新页面,即注册/成功。

总而言之,我正在尝试使用细枝模板在细长的应用程序中实现php表单验证,例如this

如果有帮助,我还将包括注册表格的register.html.twig页面:

{% extends 'header_footer.html.twig'%}
{% block content %}
    <h3>Register A New Account</h3>

    <form method = "post" action = " {{ action_register }} ">
        <p>Email: <input type="text" name="email" ><br></p>

        <p>Username: <input type="text" name="username" ><br></p>
        <span class="error">* <?php echo $nameError;?></span> //code used in the php validation guide

        <p>Password: <input type="text" name="password" ><br></p>
        <!--<p>Password Confirm: <input type="text" name="password_confirm"><br></p>  THIS WILL BE IMPLEMENTED LATER-->
        <input type="submit" value="Create Account">
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

您不能在Twig中使用PHP。

看看这些:

借助Flash和Slim-Validation,您可以实现所需的错误消息。

如果您不想使用上述组件,则只需将$nameError变量传递给模板:

PHP:

return $this->view->render($response,
  'display_user.html.twig',
  [
    'nameError' => $nameError, // HERE
    'css_path' => CSS_PATH,
    'landing_page' => $_SERVER["SCRIPT_NAME"],
    //'action_register' => 'index.php/register',
    //'initial_input_box_value' => null,
    'page_title' => 'Login App - Display',
    'username' => $cleaned_username,
    'hashed_password' => $cleaned_password,
  ]
);

嫩枝:

{% if nameError %}<span class="error">* {{ nameError }}</span>{% endif %}