CodeIgniter PHP

CodeIgniter: Check Authentication and Fail

Very often, when developing a site using CodeIgniter, I use a base Controller to check common functions such as authentication. This is easiest to do in the Controller’s __construct method. Usually you can simply use a redirect to your login page:

[code lang=”php”]
redirect( "/user/login" );

But sometimes you simply want to stop the Controller and output the fact that they are not authorised or that a certain error has occurred. I was just doing this with a REST API on a site, and simply wanted to fail if the wrong API Key was passed. I’ve found it’s easiest to do via a “show_error” call:

[code lang=”php”]
show_error(‘Not authorized’, 401 );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.