Quinlanlent Quinlanlent - 1 year ago 79
PHP Question

Prevent users from accessing a url directly Yii 2

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?

$isAdded = ActiveSubject::find()->where(['clientid' => $_user,'subjectid' => $subjects['subjectid'],])->exists();
<b><p class="text-muted">ADDED</p></b>
<?php else: ?>
<?= Html::a('<b>ADD</b>',['site/addsubject', 'subjectid'=>$subjects['subjectid'], 'clientid' => $_user],['class' => 'btn-info btn-transparent btn-large']) ?>
<?php endif; ?>
<?= $subjects['slots'] ?>
<?php if($isAdded): ?>
<p class="text-primary">Awaiting Confirmation</p>
<?php endif; ?>

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download