问题
I have this piece of code that if the user clicks on it the link will be replaced by text making it unable to be clicked again. The problem now is that if the user access it directly in the url so it will simulate a link click. So how do I prevent users from accessing urls directly?
<?php
$isAdded = ActiveSubject::find()->where(['clientid' => $_user,'subjectid' => $subjects['subjectid'],])->exists();
if($isAdded):
?>
<b><p class="text-muted">ADDED</p></b>
<?php else: ?>
<p>
<?= Html::a('<b>ADD</b>',['site/addsubject', 'subjectid'=>$subjects['subjectid'], 'clientid' => $_user],['class' => 'btn-info btn-transparent btn-large']) ?>
</p>
<?php endif; ?>
</td>
<td>
<?= $subjects['slots'] ?>
</td>
<td>
<?php if($isAdded): ?>
<p class="text-primary">Awaiting Confirmation</p>
<?php endif; ?>
回答1:
In controller
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['addsubject'],
'allow' => true,
'roles' => ['addsubject', 'yourmodelname'],
],
[
'allow' => true,
'roles' => ['superAdmin', 'admin', 'managerModule1', 'managerApp'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'addsubject' => ['post'],
],
],
];
}
checkout this 2 answers also
how to deny the access of url in yii even if we know the url?
how to limit access url view on yii2 by id
In which you can understand the use of filters.
回答2:
Make it a POST link so that it has to clicked and can't be directly run from the browser
ie.
adding 'data-method' => 'post'
to HTML::a
<?= Html::a('<b>ADD</b>',['site/addsubject', 'subjectid'=>$subjects['subjectid'], 'clientid' => $_user],['class' => 'btn-info btn-transparent btn-large', 'data-method' => 'post']) ?>
And in the Access Rules you can add rule to only accept POST Request
i.e
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'addsubject' => ['post'],
],
],
Hope this helps. Thanks.
Edit:
Below is sample for SiteController
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => True,
'actions' => [],
'roles' => []
],
[
'actions' => ['login', 'error', 'captcha'],
'allow' => true,
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
'addsubject' => ['post'],
],
],
];
}
来源:https://stackoverflow.com/questions/39092234/prevent-users-from-accessing-a-url-directly-yii-2