Yii2 Framework

Yii2 framework inventory system example

Docs » Guide » Input forms; Creating Forms. The primary way of using forms in Yii is through yiiwidgetsActiveForm. This approach should be preferred when the form is based upon a model. Additionally, there are some useful methods in yiihelpersHtml that are typically used for adding buttons and help text to any form. Find your new favorite web frameworkMeasuring web framework popularity so you can find interesting frameworks to check outRankings FrameworkGithub ScoreStack Overflow.

Uploading files in Yii is usually done with the help of yiiwebUploadedFile which encapsulates each uploadedfile as an UploadedFile object. Combined with yiiwidgetsActiveForm and models,you can easily implement a secure file uploading mechanism.

Creating Models ¶

Like working with plain text inputs, to upload a single file you would create a model class and use an attributeof the model to keep the uploaded file instance. You should also declare a validation rule to validate the file upload.For example,

Yii 3

In the code above, the imageFile attribute is used to keep the uploaded file instance. It is associated witha file validation rule which uses yiivalidatorsFileValidator to ensure a file with extension name png or jpgis uploaded. The upload() method will perform the validation and save the uploaded file on the server.

The file validator allows you to check file extensions, size, MIME type, etc. Please refer tothe Core Validators section for more details.

Tip: If you are uploading an image, you may consider using the image validator instead. The image validator is implemented via yiivalidatorsImageValidator which verifies if an attribute has received a valid image that can be then either saved or processed using the Imagine Extension.

Rendering File Input ¶

Yii framework vulnerability

Next, create a file input in a view:

It is important to remember that you add the enctype option to the form so that the file can be properly uploaded.The fileInput() call will render a <input type='file'> tag which will allow users to select a file to upload.

Tip: since version 2.0.8, fileInput adds enctype option to the form automatically when file input field is used.

Framework

Wiring Up ¶

Now in a controller action, write the code to wire up the model and the view to implement file uploading:

In the above code, when the form is submitted, the yiiwebUploadedFile::getInstance() method is calledto represent the uploaded file as an UploadedFile instance. We then rely on the model validation to make surethe uploaded file is valid and save the file on the server.

Uploading Multiple Files ¶

You can also upload multiple files at once, with some adjustments to the code listed in the previous subsections.

First you should adjust the model class by adding the maxFiles option in the file validation rule to limitthe maximum number of files allowed to upload. Setting maxFiles to 0 means there is no limit on the number of filesthat can be uploaded simultaneously. The maximum number of files allowed to be uploaded simultaneously is also limitedwith PHP directive max_file_uploads,which defaults to 20. The upload() method should also be updated to save the uploaded files one by one.

In the view file, you should add the multiple option to the fileInput() call so that the file upload fieldcan receive multiple files. You also need to change imageFiles to imageFiles[] so that the attribute values are submitted as an array:

And finally in the controller action, you should call UploadedFile::getInstances() instead of UploadedFile::getInstance() to assign an array of UploadedFile instances to UploadForm::imageFiles.

Found a typo or you think this page needs improvement?
Edit it on github !

Before start the application login steps, We must have to install the application. Use the 'Installing Yii2.0' tutorials to learn about 'how to install the yii 2.0 advanced and basic templates application'.

Config The Database

Open the main.php under the following folder structure

Add the mysql database credentials in main.php file

Add LoginForm.php Into Backend/Model

  • Copy the login form file from 'common/models/LoginForm.php' into 'backend/models/LoginForm.php'
  • Open 'backend/models/LoginForm.php' file and change the namespace details from 'namespace
    commonmodels;'
    to namespace appmodels; on top of the file.

Create User Model

Create the user model using 'Yii code generator'
backend/models/User.php

Impldements namespaces

Add the following namespaces in 'User' model class

Implements the IdentityInterface interface class with 'User' model class

Yii Framework Documentation

Add Login Process Functions

After created 'User.php' model add the following functions into 'User' model.

Assign identityClass

Default identityClass is
'commonmodelsUser'(for advanced application). Now we configured new identityClass class in 'appmodelsUser' and change it in
'backendconfigmain.php' file. Change enableAutoLogin value to false

Yii2

Change namespace in SiteController

Yii Framework Vulnerability

The login functions are available in 'SiteController.php' and we have to change 'LoginForm' namespace. Find the 'use
commonmodelsLoginForm;'
and replace the 'use appmodelsLoginForm;'
Now you can login from database 'user' table for yii 2.0 applicatons.

Yii2 Tutorial

User.php Model

Yii2 Advanced Framework

  • Luis M

    hi, i have problem error :

    Declaration of appmodelsUser::findIdentityByAccessToken() must be compatible with yiiwebIdentityInterface::findIdentityByAccessToken($token, $type = NULL)

    • edit : appmodelsUser::findIdentityByAccessToken() for appmodelsUser::findIdentityByAccessToken($token, $type = NULL) and add return static::findOne([‘access_token’ => $token]);

      • Did you get this fixed? can you plz explain how you fixed?

        • im edit user.php and change for
          public static function findIdentityByAccessToken($token, $type = null)
          {
          return static::findOne([‘access_token’ => $token]);
          }

  • UTEHN PHNU

    i face this error message.
    “Unknown Property – yiibaseUnknownPropertyException

    Getting unknown property: appmodelsUser::auth_key”

    • thanks!

      how I get user session I use Yii::$app->user->identit->username it not work.

      • use this “Yii::$app->user->identity->username”. You missed ‘y’ in identity

        • I mean Yii::$app->user->identity->username ,it not work

  • mmm i have problem im not implement correctly yii2 session any example ?? im access to url and enter to views im not logg.

  • wheres “app” in your text you write app/models/User

  • i tried the above coding but i have a error.simply username or password invalid.
    in main.php
    [],
    ‘components’ => [
    ‘db’=>[
    ‘class’=>’yiidbConnection’,
    ‘dsn’ => ‘mysql:host=localhost;dbname=fms’,
    ‘username’ => ‘root’,
    ‘password’ => ”,
    ‘charset’ => ‘utf8’
    ],
    ‘user’ => [
    ‘identityClass’ => ‘commonmodelsUser’,
    ‘enableAutoLogin’ => false,
    ],

    ?>
    User.php
    100]
    ];
    }

    /**
    36 * @inheritdoc
    37 */
    public function attributeLabels()
    {
    return [
    ‘userid’ => ‘Userid’,
    ‘username’ => ‘Username’,
    ‘password’ => ‘Password’
    ];
    }

    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
    /**
    003 * @inheritdoc
    004 */
    public static function findIdentity($id)
    {
    return static::findOne($id);
    }
    /**
    011 * @inheritdoc
    012 */
    /* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
    return static::findOne([‘access_token’ => $token]);
    }

    /* removed
    020 public static function findIdentityByAccessToken($token)
    021 {
    022 throw new NotSupportedException(‘”findIdentityByAccessToken” is not implemented.’);
    023 }
    024 */
    /**
    026 * Finds user by username
    027 *
    028 * @param string $username
    029 * @return static null
    030 */
    public static function findByUsername($username)
    {
    return static::findOne([‘username’ => $username]);
    }

    /**
    037 * Finds user by password reset token
    038 *
    039 * @param string $token password reset token
    040 * @return static null
    041 */
    public static function findByPasswordResetToken($token)
    {
    $expire = Yii::$app->params[‘user.passwordResetTokenExpire’];
    $parts = explode(‘_’, $token);
    $timestamp = (int) end($parts);
    if ($timestamp + $expire $token
    ]);
    }

    /**
    058 * @inheritdoc
    059 */
    public function getId()
    {
    return $this->getPrimaryKey();
    }

    /**
    066 * @inheritdoc
    067 */
    public function getAuthKey()
    {
    return $this->auth_key;
    }

    /**
    074 * @inheritdoc
    075 */
    public function validateAuthKey($authKey)
    {
    return $this->getAuthKey() $authKey;
    }

    /**
    082 * Validates password
    083 *
    084 * @param string $password password to validate
    085 * @return boolean if password provided is valid for current user
    086 */
    public function validatePassword($password)
    { return $this->password sha1($password);
    return Security::validatePassword($password, $this->password_hash);
    }

    /**
    094 * Generates password hash from password and sets it to the model
    095 *
    096 * @param string $password
    097 */
    public function setPassword($password)
    {
    $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
    104 * Generates “remember me” authentication key
    105 */
    public function generateAuthKey()
    {
    $this->auth_key = Security::generateRandomKey(); }

    /**
    112 * Generates new password reset token
    113 */
    public function generatePasswordResetToken()
    {
    $this->password_reset_token = Security::generateRandomKey() . ‘_’ . time();
    }

    /**
    120 * Removes password reset token
    121 */
    public function removePasswordResetToken()
    {
    $this->password_reset_token = null; }
    }

    in my db table is

    userid pk AI
    username varchar100
    password varchar100

    what can i do further.

    please help me.

    thanks in advance

  • this doesn’t work for me, i get redirected and i am always guest even if everything seems ok. can you help me providing a working example? thanks

    • Add the below code in config/web.php
      ‘user’ => [
      ‘identityClass’ => ‘appmodelsUser’,

      ….

  • Not working still takes the User.php on common path and when i replace it with the one i need i got this error : ”
    Cannot redeclare commonmodelsUser::validatePassword()”

    • In config/web.php
      ‘user’ => [
      ‘identityClass’ => ‘appmodelsUser’,….

      • You mean in config/main-local.php i did this now its throwing invalid username or password

        • It’s working thank you, to those who may face this, the problem was validatePassword() function just remove sha1()

          • Do not rremove sha1(). just do this:

            return trim($this->password) sha1($password);

          • This hasn’t worked for me, still throwing invalid username or password. All suggestions welcome. Thanks.

      • Now its using the right User.php & Loginform.php but it keeps throwing “Incorrect username or password ” do you have any idea what may cause the problem ??

  • Hello,

    I have a problem when I set enableAutoLogin to false: the login screen is the only one that I see. But if I set it to true, I works perfectly. Any idea ? Any help is welcome.

    Thanks

  • Thanks, I was skipping the steps at “Assign identityClass” until I got your tutorial.

  • Dipanshu Mahajan

    How can we signup new user so that we can use login

  • Can you share de Security helper class implementation?
    Thanks.

  • hello mr.

    after I followed the above article
    i have problem, i can’t login with database and i can’t with admin and demo.

    is there any idea, I have to how or what I need to make changes?

    please help me..
    Thanks

  • how validate login with 2 table, which is table user and table customer?.
    if login as user will redirect to backend, if login as customer will be redirect to frontend.

    What should i do?.

  • can we use user table having columns like Username,Password (PascalCasing)