后端應(yīng)該對前端數(shù)據(jù)來源渠道進行驗證
后端進行數(shù)據(jù)的操作時,往往要根據(jù)前端提交過來的數(shù)據(jù)和命令進行不同的操作,必須要判斷來源渠道。
1、來源渠道有幾種
get,post,put,delete等,最常見的是get和post
get是明文傳遞,post會進行一定的加密。get一般是用來查詢數(shù)據(jù)的,post提交數(shù)據(jù)。
2、驗證來源
1)后臺如果僅僅是顯示數(shù)據(jù),倒無所謂,本來你用get傳遞數(shù)據(jù),有人如果用post偽造一個訪問,結(jié)果差不多。
2)后臺如果是修改或者刪除數(shù)據(jù),必須進行來源限制
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
// 正常業(yè)務(wù)邏輯
return json_encode(['data' => []]);
}
public function store()
{
$this->validateMethod(['POST', 'PUT']); // 允許多個方法
// 正常業(yè)務(wù)邏輯
}
}
3)if判斷
if($this->request->isAjax()){
// 正常業(yè)務(wù)邏輯
}

浙公網(wǎng)安備 33010602011771號