This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

User Authentication in Yii2 with Email verification

Updated on July 15, 2021

5 Min Read

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.

user authentication in yii2

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',
   ],
],

paste your code

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.

apply the migrations?

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:

select your SMTP host

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

                     ],

paste your code here

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.

POP IMAP

Test the App

The app is now ready for testing. Fire up the application in the browser and load the signup page.

test the app

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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

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.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now