后端进行数据的操作时,往往要根据前端提交过来的数据和命令进行不同的操作,必须要判断来源渠道。
1、来源渠道有几种
get,post,put,delete等,最常见的是get和post
get是明文传递,post会进行一定的加密。get一般是用来查询数据的,post提交数据。
2、验证来源
1)后台如果仅仅是显示数据,倒无所谓,本来你用get传递数据,有人如果用post伪造一个访问,结果差不多。
2)后台如果是修改或者删除数据,必须进行来源限制
3、几种办法
1)路由
$router->get('/users', 'UserController@index'); // 只允许GET $router->post('/users', 'UserController@store'); // 只允许POST $router->put('/users/{id}', 'UserController@update'); // 只允许PUT
2)中间件
abstract class Controller {protected $request;/*** 验证HTTP方法*/protected function validateMethod($allowedMethods){if (!in_array($this->request->getMethod(), (array)$allowedMethods)) {http_response_code(405);echo json_encode(['code' => 405,'msg' => 'Method Not Allowed','allowed_methods' => (array)$allowedMethods]);exit;}} }// 在子类中使用 class UserController extends Controller {public function index(){$this->validateMethod('GET'); // 只允许GET// 正常业务逻辑return json_encode(['data' => []]);}public function store(){$this->validateMethod(['POST', 'PUT']); // 允许多个方法// 正常业务逻辑} }
3)if判断
if($this->request->isAjax()){
// 正常业务逻辑
}