User authentication is an essential component of every web app. Whether it is a simple to-do list or a complex corporate portal, user authentication remains a common factor across all types of PHP applications.
In this tutorial, I will show you how to develop a user authentication component in Yii2 that features a SMTP email verification. If you are new to Yii2, you must first read previous tutorials to get an introduction to Yii2. Next read about form handling in Yii 2 and database management in Yii 2.
Yii2’s application template offers several methods for user registration. However, these default methods are not very useful as they depend upon hard-coded values. For practical reasons, this system must use a database for user information storage and protect the passwords through hashtags.
Another way of implementing user authentication in Yii2 is to use third-party extensions. For the purpose of this tutorial, I will use Dmitry Erofeev’s  Yii2-User extension. For more information on this extension, you could read the extension’s documentation.
Create a New project
I will begin by creating a basic Yii2 project using Composer:
composer create-project --prefer-dist yiisoft/yii2-app-basic newuser
Now that the project has been created, I will now install the extension.
Install the Yii2-User
I will follow the the installation guide from the official documentation of the extension.
Go into the project folder and execute following Composer command:
composer require dektrium/yii2-user
Next, I will set several configurations. For this, open `config / web.php`Â and add the following lines:
'modules' => [ Â Â Â 'user' => [ Â Â Â Â Â Â Â 'class' => 'dektrium\user\Module', Â Â Â ], ],
Database Creation and Migration
Next, create a database with the name `newuser`. For this, go to `config/db.php` and set the database (see the following screenshot:
The next step is database migration. For this, use the following composer command:
php yii migrate/up --migrationPath=@vendor/dektrium/yii2-user/migrations
After the successful migration your database is ready to be used for user authentication.
Setup SMTP Mailer
The next step is the setup of the SMTP mailer. This mailer will generate the verification emails.
For this setup, open Config / web.php and search for the following code snippet:
'mailer' => [    'class' => 'yii\swiftmailer\Mailer',    // send all mails to a file by default. You have to set    // 'useFileTransport' to false and configure a transport    // for the mailer to send real emails.    'useFileTransport' => true, ],
Once you have found the snippet, replace it with the following code snippet: Â
'mailer' => [ Â Â Â Â Â Â Â 'class' => 'yii\swiftmailer\Mailer', Â Â Â Â Â Â Â 'viewPath' => '@app/mailer', Â Â Â Â Â Â Â 'useFileTransport' => false, Â Â Â Â Â Â Â 'transport' => [ Â Â Â Â Â Â Â Â Â Â Â 'class' => 'Swift_SmtpTransport', Â Â Â Â Â Â Â Â Â Â Â 'host' => 'your-host-domain e.g. smtp.gmail.com', Â Â Â Â Â Â Â Â Â Â Â 'username' => 'your-email-or-username', Â Â Â Â Â Â Â Â Â Â Â 'password' => 'your-password', Â Â Â Â Â Â Â Â Â Â Â 'port' => '587', Â Â Â Â Â Â Â Â Â Â Â 'encryption' => 'tls', Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ], Â Â Â ],
As you can see, you need to provide several information including the SMTP host, a valid email and password. Refer to the following screenshot to check snippet placement:
At this point, everything is ready and all that is required are the access links to the sign in and sign up pages. I will now modify the main layout file.
Go to the `Views/layouts /main.php`Â and search for the following code snippet:
echo Nav::widget([ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'options' => ['class' => 'navbar-nav navbar-right'], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'items' => [ Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'Home', 'url' => ['/site/index']], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'Status', 'url' => ['/status/index']], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'About', 'url' => ['/site/about']], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'Contact', 'url' => ['/site/contact']], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Yii::$app->user->isGuest ? Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'Login', 'url' => ['/site/login']] : Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ['label' => 'Logout (' . Yii::$app->user->identity->username . ')', Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'url' => ['/site/logout'], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â 'linkOptions' => ['data-method' => 'post']], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â ], Â Â Â Â Â Â Â Â Â Â Â ]);
Replace this snippet with the following array definition:
$navItems=[ Â Â Â ['label' => 'Home', 'url' => ['/site/index']], Â Â Â ['label' => 'Status', 'url' => ['/status/index']], Â Â Â ['label' => 'About', 'url' => ['/site/about']], Â Â Â ['label' => 'Contact', 'url' => ['/site/contact']] Â ]; Â if (Yii::$app->user->isGuest) { Â Â Â array_push($navItems,['label' => 'Sign In', 'url' => ['/user/login']],['label' => 'Sign Up', 'url' => ['/user/register']]); Â } else { Â Â Â array_push($navItems,['label' => 'Logout (' . Yii::$app->user->identity->username . ')', Â Â Â Â Â Â Â 'url' => ['/site/logout'], Â Â Â Â Â Â Â 'linkOptions' => ['data-method' => 'post']] Â Â Â ); Â } echo Nav::widget([ Â Â Â 'options' => ['class' => 'navbar-nav navbar-right'], Â Â Â 'items' => $navItems, ]);
Turn on Pretty URL
Now, in order to make these links work, I will turn the pretty URL on . Pretty URL are cleaner format of the URL that are easier to rea. For instance, the URL structure of  the About page could be: http://localhost/newuser/web/index.php?r=site/about. The Pretty URL version of this URL will be: http://localhost/newuser/web/site/about.
In order to achieve this, go to `Config/web.php`Â and add the following code in the components.
'urlManager' => [              'showScriptName' => false,              'enablePrettyUrl' => true                      ],
Now open the web folder and create a new file with the name of .htaccess. Open this file and add the following code into it:
RewriteEngine on # If a directory or a file exists, use it directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Otherwise forward it to index.php RewriteRule . index.php
Configure the Email Settings
Note: Gmail is the default email provider for this example.
Login to Gmail using the credentials mentioned in the code above.
Go to Settings >> Forwarding and POP/IMAP and enable the IMAP Access.
Test the App
The app is now ready for testing. Fire up the application in the browser and load the signup page.
Fill in the form and click Sign up. A verification email will also be sent to the email you provided during the signup.
Lastly, go to Unlock Google Captcha and turn it on. Now reload the signup page , fill in the form and finish the registration process.
Conclusion
In this tutorial, I described how you could setup a user authentication system in Yii2. I also added email verification and password hashing as additional security measures. If you have an queries or would like to contribute to the discussion, do leave a comment below.
Saquib Rizwan
Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends.