<?php
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
'flag-as-spammer' => ['post'], // added for actionFlagAsSpammer
],
],
];
}
...
public function actionFlagAsSpammer() {
$id = Yii::$app->request->post('id');
if ($id === null) {
throw new yii\web\BadRequestHttpException("The 'id' parameter is missing.");
}
$user = User::find()->where(['id' => $id])->one();
if ($user === null) {
throw new NotFoundHttpException("The requested user [$id] was not found.");
}
$user->spammer = true;
$user->save(false);
...
}
?>
The verb filter ensures the "flag-as-spammer" action is called with POST method. It will throw yii\web\MethodNotAllowedHttpException if the method is not POST.
Usually you don’t need to mind about the error view. Each error message of the exceptions will be displayed in the ready made error view that is a part of the application template.
And from the security point of view, there’s no need to worry about the value of ‘id’, because “where([‘id’ => $id])” will use the parameter binding. In fact, you can safely pass “1972; delete * from user;” as $id without fearing a sql injection. The query will only return null as $user, and that’s all that will happen.