コード例 #1
0
 /**
  * logs the user in (setting $_SESSION['id_user']), throws exception if anything happens
  *
  * @param string $user_username
  * @param string $user_password
  * @param bool $remember
  * @throws LoginException
  * @return bool, true if successfull
  */
 public static function login($user_username, $user_password, $remember)
 {
     // check username
     if (!preg_match("/^([a-zA-Z]+[a-zA-Z0-9]{3,})?\$/", $user_username)) {
         throw new LoginException('Username not valid.');
     }
     // check password
     if (!preg_match("/^([a-zA-Z0-9\$%'-]{5,})?\$/", $user_password)) {
         throw new LoginException('Password not valid.');
     }
     if (empty($user_username) || empty($user_password)) {
         throw new LoginException('Enter username and password.');
     }
     // try to log in
     try {
         $user = ModelUser::login($user_username, $user_password);
     } catch (LoginException $ex) {
         throw $ex;
     }
     // The log-in is OK so set the user ID and username cookies, and redirect to the home page
     $_SESSION['id_user'] = $user->getUserId();
     // set cookie
     if ($remember) {
         $auth_token = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, USER_TOKEN_MAX_LENGTH);
         $user->setToken($auth_token);
         setcookie('user_token', $auth_token, time() + 60 * 60 * 24 * 30, ABS_REF_PREFIX);
     }
     return true;
 }