Using controller filters

In many cases, we need to filter the incoming data or perform some actions based on the data. For example, with custom filters, we can filter visitors by IP, force users to use HTTPS, or redirect the user to an installation page prior to using the application.

In Yii2, filters are essentially a special kind of behavior, so using filters is the same as using behaviors.

Yii has a lot of built-in usable filters, which include:

  • Core
  • Custom
  • Authentication
  • Content Negotiator
  • HttpCache
  • PageCache
  • RateLimiter
  • Verb
  • Cors

In this recipe, we will implement the following:

  • Limiting access to the controller action to authorized users only
  • Limiting access to the controller action to specified IPs
  • Limiting access to specific user roles

Getting ready

  1. Create ...

Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.