title: Yii2 register and auto login
body: <p>My problem is: I have a buy now form and I need to register and log in the user before I redirect to the bank's payment page. All the details from is in a bootstrap modal, and I send it with jQuery post (<code>$.post()</code>).</p>
  
  <p>My User class in Yii2: <code>class User extends ActiveRecord implements IdentityInterface</code></p>
  
  <p>And here is the register and login:</p>
  
  <pre><code>$user = new User();
  $user-&gt;email = $email;
  $user-&gt;password = $password;
  if($user-&gt;save()) {
      \Yii::$app-&gt;user-&gt;login($user, 3600 * 24 * 30)
  }
  </code></pre>
  
  <p>The user created, but if I relad the page, it's still not logged in. The <code>\Yii::$app-&gt;user-&gt;login()</code> returns with true.</p>
  
  <p>I tried to put this before the login:</p>
  
  <pre><code>$session = \Yii::$app-&gt;session;
  if (!$session-&gt;isActive) {
      $session-&gt;open();
  }
  </code></pre>
  
  <p>But not helped. I'm sure the problem is the ajax login but how can I do it right?</p>
  
  <p>EDIT:</p>
  
  <p>I have created a test:</p>
  
  <pre><code>public function actionLoginTest()
  {
      $session = \Yii::$app-&gt;session;
      $session-&gt;open();
  
      $user = User::findOne(163);
      echo '&lt;pre&gt;';
      echo 'logged before login: ' . (int) \Yii::$app-&gt;user-&gt;getId() . PHP_EOL;
      echo 'isGuest before login: ' . (\Yii::$app-&gt;user-&gt;isGuest ? 'yes' : 'no') . PHP_EOL;
      \Yii::$app-&gt;user-&gt;login($user, 3600 * 24 * 30);
      echo 'isGuest after login: ' . (\Yii::$app-&gt;user-&gt;isGuest ? 'yes' : 'no') . PHP_EOL;
      echo 'logged user: ' . \Yii::$app-&gt;user-&gt;getId();
  }
  </code></pre>
  
  <p>This is the response on every reload:</p>
  
  <pre><code>logged before login: 0
  isGuest before login: yes
  isGuest after login: no
  logged user: 163
  </code></pre>
  
  <p>So never login...</p>