How to Create Authentication Features (Register & Login) in Codeigniter 4

How to Create Authentication Features (Register & Login) in Codeigniter 4

Admin
Admin・ 24 Agustus 2021
10 min read ・ 2982 views

Authentication Codeigniter 4 - In this article, we will share a tutorial on how to create an authentication feature or register and login feature using the codeigniter framework version 4. This article is also the first article published in the codeigniter 4 tutorial series. In this article we will also try to explain from the basics about codeigniter 4 and hope it is also easy to understand for beginners.

Some points that we will learn in this article:

  1. Install Codeigniter via Composer
  2. Creating a Register Feature
  3. Creating a Login Feature

What to prepare:

  1. Browser (ex: Google Chrome)
  2. Code Editor(ex: Visual Studio Code)
  3. Composer
  4. Local Server (ex: XAMPP)
  5. Internet

What is Codeigniter?

Codeigniter is an Application Development Framework or toolkit for developers who are building a website or web-based application using PHP. The purpose of making codeigniter is to help develop a project faster than starting it by creating or writing code from scratch, with the availability of libraries to do tasks that are generally needed, as well as a simple interface and logical structure to access the library. Codeigniter lets us creatively focus on our projects by minimizing the amount of code required for a given task.

Codeigniter is made to be as flexible as possible, allowing us to work the way we want, not being forced to work a certain way. The Codeigniter framework has core parts that can easily be expanded or completely replaced to make the system work the way we need it. In short, codeigniter is a framework that tries to provide the tools we need.

Is Codeigniter Right for You?

Codeigniter is right for you if:

  1. You need a framework with a small footprint.
  2. You need a system with outstanding performance or performance.
  3. You want a minimal configuration framework.
  4. You want a framework that doesn't require using the command line.
  5. You want a framework that is flexible or doesn't require you to follow coding rules.
  6. You're not interested in large-scale monolithic libraries like PEAR.
  7. You don't want to be forced to learn a templating language.
  8. You avoid complexity or like simple solutions.
  9. You need clear and thorough documentation.

Source: Codeigniter

Why need authentication feature?

If we create programs or systems such as online stores, market places, information systems and others that contain important data such as documents, user data and other important data, we need to create an authentication feature to provide data security or so that our data not taken by irresponsible people who can be abused.

Creating Authentication Features with Codeigniter 4

Alright, let's just get into coding, starting with installing codeigniter version 4 via composer 🚀

Install Codeigniter

Since codeigniter 4 was released, it is now possible to install codeigniter via composer (same as installing laravel). So how to install Codeigniter 4 can be done in several different ways, namely manually, installing with composer or using Git. In this article we will try it by installing codeigniter via composer, but if you want to use the manual method that's fine too.

composer create-project codeigniter4/appstarter codeigniter4

To install codeigniter 4 via composer, you can just open a terminal and then go to the directory where we want to put or install this codeigniter 4 project. Then, run the command as above in the terminal. With the command as above, we will install codeigniter 4 which we will name codeigniter4. What will happen if we don't include codeigniter4 when install codeigniter 4 via composer ? if we just run the command composer create-project codeigniter4/appstarter then the installation process can still run and will create us a codeigniter 4 project folder with the name appstarter.

Error saat install codeigniter 4 via composer

If in the codeigniter 4 installation process via composer an error occurs as shown above, it's because the PHP you are using does not have an intl extension. The intl extension is useful for formatting currency or currency, numbers and dates or times as well as UCA-compliant arrangements, for message formatting and text normalization and so on. If you are using XAMPP as your local server, try following the steps below:

  1. Open the php.ini file which is located in the [xampp_folder_path]/php/php.ini directory.
  2. Look for ;extension=intl and remove the character ;
  3. Save, then restart Apache

After the installation process is complete, we can now open our codeigniter project with the php spark serve command. Open our codeigniter 4 project in browser with url http://localhost:8080.

Creating a Codeigniter 4 Database Connection

Before continuing the tutorial on making the authentication feature or registering and logging in in codeigniter 4, we will first create a new database and then adjust the configuration. If you are using XAMPP, please create a new database at localhost/phpmyadmin. For example, we will create a new database with the name codeigniter-4.

Then, we need to adjust the configuration in the env file. Please open the env file, look for records like the one below

# CI_ENVIRONMENT = production

remove the hash mark (#), then change it to development as below.

CI_ENVIRONMENT = development

Then look for the database configuration record as below

# database.default.hostname = localhost
# database.default.database = ci4
# database.default.username = root
# database.default.password = root
# database.default.DBDriver = MySQLi
# database.default.DBPrefix =

remove the hash mark (#), then adjust the database.default.database record with the name of the database you just created and also adjust the username and password. So the database configuration record will be like below.

database.default.hostname = localhost
database.default.database = codeigniter-4
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi
database.default.DBPrefix =

Okay, now the codeigniter 4 project has been successfully connected or connected to the database. Next we will try the migration feature of codeigniter 4.

Download and Install myth-auth package

In this tutorial article on creating authentication in codeigniter 4, we will use the myth-auth package to speed up the creation of authentication features (register and login).

cd app/ThirdParty
git clone https://github.com/lonnieezell/myth-auth.git

First enter the ThridParty directory with the command cd app/ThirdParty, then run git clone https://github.com/lonnieezell/myth-auth.git to start installing or cloning the myth auth package.

Migrate

cd ../..
php spark migrate all

If the process of downloading or cloning the myth-auth package has been completed, we can return to the root directory with the cd ../.. command then run the php spark migrate all command to migrate the migration files (including the default migration file myth-auth packagee) to the database which we created in the previous step.

Update Autoload.php

public $psr4 = [
		APP_NAMESPACE => APPPATH, // For custom app namespace
		'Config'      => APPPATH . 'Config',
		'App'         => APPPATH,
		'Myth\Auth'   => APPPATH .'ThirdParty/myth-auth/src',
	];

Now open the app/Config/Autoload.php file, then in the $psr4 update method like the script above. In this step, we add 'App' => APPPATH and 'Myth\Auth' => APPPATH. 'ThirdParty/myth-auth/src' .

Update Filter.php

public $aliases = [
		'csrf'     => CSRF::class,
		'toolbar'  => DebugToolbar::class,
		'honeypot' => Honeypot::class,
		'login'      => \Myth\Auth\Filters\LoginFilter::class,
		'role'       => \Myth\Auth\Filters\RoleFilter::class,
		'permission' => \Myth\Auth\Filters\PermissionFilter::class,
	];

TThen open the app/Config/Filter.php file, update $aliases with the addition of the script as above.

Update Routes.php

$routes->get('/', 'Home::index');
$routes->group('', ['filter' => 'login'], function($routes){
    $routes->get('home', 'Home::home');
});

Next, open the app/Config/Routes.php file and add a new route with the script as above.

Update Email.php

public $fromEmail = "codelapancom@gmail.com";
public $fromName = "codelapan";

In the app/Config/Email.php file or more precisely in the $fromEmail and $fromName sections, please adjust your email and name as in the example script above. The script above is an email setting that is used to send emails such as email verification, forgot password and other features that use email.

Update Validation.php

public $ruleSets = [
	Rules::class,
	FormatRules::class,
	FileRules::class,
	CreditCardRules::class,
	\Myth\Auth\Authentication\Passwords\ValidationRules::class,
];

Still in the config area, this time we need to add a script in the Validation.php file. Please open the file, then update or add the $ruleSets script like the example above.

Update Config/Auth.php

public $requireActivation = null;

Okay, almost done. Now open the Auth.php file which is located in the app/ThirdParty/myth-auth/src/Config directory. In the public $requireActivation section, change the value to null. What is the function of the script? the script serves to create an email verification feature for user activation. Because in this tutorial we only try it locally, so I think there is no need for email activation.

Codeigniter 4 Authentication Testing

After going through quite long but not too difficult steps, starting from installing codeigniter 4 via composer, installing or clone myth auth package, up to setting up config files, now we have arrived at testing the authentication feature of codeigniter 4.

To start seeing the results of what we made, please run codeigniter with the php spark serve command. Then open it in a browser with the URL localhost:8080/register and try to fill in the data in the available forms such as email, username and password then click register.

We have succeeded in creating the authentication feature in codeigniter 4 using the myth auth package and in the testing step we have also successfully registered and logged in.

Good luck, hopefully this article can be useful and see you in the next article.🚀 🚀 🚀

 

Credit: Work illustrations by Storyset

 

Tinggalkan Komentar
Loading Comments