php服务器端验证返回数据

时间:2016-02-01 18:48:11

标签: php

在我的php项目中,我使用了用this tutorial创建的简单mvc。

这是我的 Bootstrap.php 文件

<?php
class Bootstrap {

    private $_url = null;
    private $_controller = null;

    private $_controllerPath = 'controllers/';
    private $_modelPath = 'models/';
    private $_errorFile = 'error.php';
    private $_defaultFile = 'home.php';

    public function init(){
        $this->_getUrl();

        if(empty($this->_url[0])){
            $this->_loadDefaultController();
            return false;
        }   

        $this->_loadExistingController();
        $this->_callControllerMethod(); 
    }

    private function _getUrl(){
        $url = isset($_GET['url']) ? $_GET['url'] : null;
        $url = rtrim($url, '/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $this->_url = explode('/', $url);
    }

    private function _loadDefaultController() {
        require $this->_controllerPath . $this->_defaultFile;
        $this->_controller = new Home();
        $this->_controller->index();    
    }

    private function _loadExistingController() {
        $file = $this->_controllerPath . $this->_url[0] . '.php';

        if(file_exists($file)) {
            require $file;
            $this->_controller = new $this->_url[0];
            $this->_controller->loadModel($this->_url[0], $this->_modelPath);   
        } else {
            $this->_error();
            return false;
        }           
    }

    private function _callControllerMethod() {
        if(isset($this->_url[2])) {
            if(method_exists($this->_controller, $this->_url[1])) {
                $this->_controller->{$this->_url[1]}($this->_url[2]);
            } else {
                $this->_error();
            }
        } else {
            if(isset($this->_url[1])) {
                if(method_exists($this->_controller, $this->_url[1])) {
                    $this->_controller->{$this->_url[1]}();
                } else {
                    $this->_error();
                }
            } else {
                $this->_controller->index();
            }
        }
    }

    private function _error() {
        require $this->_controllerPath . $this->_errorFile;
        $this->_controller = new Error();
        $this->_controller->index();
        exit;
    }
}

控制器

<?php
class Controller {
    function __construct() {
        $this->view = new View();           
    }

    public function loadModel($name, $modelPath = 'models/') {
        $path = $modelPath . $name .'_model.php';

        if(file_exists($path)) {
            require $modelPath . $name .'_model.php';

            $modelName = $name . '_Model';
            $this->model = new $modelName();
        }
    }
}

用户控制器

<?php
class User extends Controller {
    function __construct(){
        parent::__construct();          
    }

    public function registration() {
        $this->view->render('user/registration');
    }

    public function enter() {
        $this->view->render('user/enter');
    }

    public function create() {
        $data = array();
        $data['name'] = $_POST['name'];
        $data['password'] = $_POST['password'];
        $data['role'] = 2;

        $this->model->create($data);            
        header('location: ' . URL);
    }

}

我添加了客户端验证(namepassword字段不能为空)但我也想添加服务器端验证,但我不明白这里如何返回数据是否会发现错误返回查看?我想,我需要从正确填充的字段中返回错误和数据。

2 个答案:

答案 0 :(得分:2)

使用会话传递验证错误。这是一个例子......

$_SESSION['error'] = array(
    'message' => 'Invalid username/password combination',
    'for' => 'login-form',
    'variables' => array(
        'username' => $_POST['username'],
    ),
);

然后在前端,您可以检查会话是否包含错误变量或您选择命名它的任何内容。如果是,您可以继续打印错误。

我实际上为我正在制作的大学课程制作了类似的轻量级框架,并查看了一些代码可能对您有所帮助。 Check it out.

在您的申请背景下进一步解释这一点......

class User extends Controller {

    ...

    public function create() {
        $data = array();
        $data['name'] = $_POST['name'];
        $data['password'] = $_POST['password'];
        $data['role'] = 2;

        // lets assume that the create method on the model will return true when it is successfully created,
        // and then false in the event that there was an error when creating/inserting it.  I am assuming that
        // the session has already been created.
        if (!$this->model->create($data)) {
            // there was an error so lets set the error message
            $_SESSION['errors'] = [
                'form' => 'user-create',
                'message' => 'There was an error creating the user',
            ];
        }

        header('location: ' . URL);
    }

}

我假设你已经开始了一个会话。如果会话不存在,则无法在会话中设置变量。要解决此问题,请在bootstrapping / index文件中使用session_start()。

然后在您的视图中,您可以使用类似代码检查错误...

if (isset($_SESSION['error']) && count($_SESSION['error']) > 0) {
    echo '<ul>';
    foreach ($_SESSION['error'] as $error) {
        echo '<li>' . $error['messsage'] . '</li>';
    }
    echo '</ul>';
}

这将检查它们是否是错误集(有几种方法可以做到这一点,但我总是只计算错误)。然后我们可以遍历每个错误并将其打印为HTML无序列表供用户查看。

答案 1 :(得分:1)

要扩展我的评论,您可以尝试使用查询参数和$_GET超全局。例如,在您的控制器中:

<?php
class User extends Controller {
    function __construct(){
        parent::__construct(); //This isn't needed as it's redundant           
    }

    public function registration() {
        $this->view->render('user/registration');
    }

    public function enter() {
        $this->view->render('user/enter');
    }

    public function create() {
        $name = isset($_POST['name']) ? $_POST['name'] : "";
        $password = isset($_POST['password']) ? $_POST['password'] : "";
        if(empty($name) || empty($password)){
            //Redirect to your login form with the query parameter
            //errorMessage which will be used with $_GET
            header('Location: loginPage.php?errorMessage=Username and password cannot be empty!');
            exit();
        }
        $data = array();
        $data['name'] = $_POST['name'];
        $data['password'] = $_POST['password'];
        $data['role'] = 2;

        $this->model->create($data);            
        header('location: ' . URL);
    }

}

然后在包含表单的页面上,您可以执行以下操作:

<?php
//This is loginPage.php from the controller example
//Other code up here if you have it

if(isset($_GET['errorMessage'])){
    //If there is a query parameter with the key 'errorMessage'
    //it will echo this out
    echo '<span class="error">' . $_GET['errorMessage'] . '</span>';
}
?>
<form>
    <input type="text" name="password" />
    <input type="password" name="name" />
</form>

有关$_GET here

的更多信息