在PHP中处理POST请求的最佳实践

时间:2019-07-20 15:42:04

标签: php post

我正在研究一个PHP项目,该项目有许多页面调用POST请求,例如登录,注册,注释等。

我尝试在名为post.php的单个文件中处理所有POST请求,每个请求都包含'formtype'参数,就像这样,

$formtype = $_POST['formtype'];
if ($formtype == "register") {
    register_function_here();
} else if ($formtype == 'login') {
    login_function_here();
} else {
    die("Error: No FORMTYPE");
}

并且我还尝试过为单独的功能提供单独的文件,例如login.php,register.php,comment.php等。

哪种方法更适合处理POST请求? 正如我所做的那样,在单个文件中处理所有POST请求是否有任何不利之处?

谢谢!

2 个答案:

答案 0 :(得分:0)

我想你是说你不想:

GET index.php
POST user/register.php
POST user/login.php

index.php
user/
    register.php
    login.php
404.php

关于MVC(模型,视图,控制器)的@ArtisticPhoenix实际上是您尝试的。好吧,对于控制器部分,我的意思是。 您尝试创建路由器

您可以这样做。如果您不熟悉编码并且有时间,我什至会说:做到这一点。 如果您没有时间需要解决方案,那么我建议您搜索一个框架-至少要进行路由。


开始使用:

我首先发现的是:https://www.taniarascia.com/the-simplest-php-router/

如果您想走得更远,则应该开始使用OOP。 一个类就是一个控制器,一个方法就是一个动作。 (有些动作就像zend表达框架一样)。

示例:

创建路由配置

// file: config/routes.php
return [
    'routes' => [
        [
            'path'            => "/login",
            'class'           => LoginController::class,
            'method'          => 'loginAction',
            'allowed_methods' => ['POST'],
        ],
        [
            'path'            => "/logout",
            'class'           => LoginController::class,
            'method'          => 'logoutAction',
            'allowed_methods' => ['GET', 'POST'],
        ],
        // ...
    ],
];

创建控制器

// file: Controller/LoginController.php
namespace Controller;
class LoginController
{
    public function loginAction()
    {
        // ...
    }

    public function logoutAction()
    {
        // ...
    }
}

现在使用请求的路径并将其route到控制器。

如果未找到路由,则返回HTTP 404“未找到”响应。

// file: index.php
// load routing config
$routes = require 'config/routes.php';
// ...
// ... this now is up to you. 
// you should search in the config if the requested path exists
// and if the request is in the allowed_methods
// and then create a new controller and call the method.

答案 1 :(得分:-1)

我强烈建议使用类,每个类一个源文件。