PHP 服务器端验证返回数据


php server side validation return data

在我的php项目中,我使用本教程创建的简单mvc。

这是我的引导.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字段不得为空(,但我也想添加服务器端验证,但我不明白如果发现错误如何返回数据查看?我想,我需要从正确填充的字段中返回错误和数据。

使用会话传递验证错误。 下面是一个示例...

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

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

实际上,我为

我正在参加的大学课程制作了一个类似的轻量级框架,浏览一些代码可能会对您有所帮助。 看看吧。

为了在您的应用程序上下文中进一步解释这一点...

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);
    }
}

我假设您已经开始了一个会话。 如果会话不存在,则无法在会话上设置变量。 要解决此问题,请在引导/索引文件中使用 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 无序列表供用户查看。

要扩展我的评论,您可以尝试使用查询参数和超全局$_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 的更多信息,请点击此处