0017

CodeIgniter2.XでSimpleLoginを使う

CodeIgniter2.XでSimpleLoginを使う

2011.3.27

CodeIgniterにはSimpleLoginという、名前の通りシンプルな認証ライブラリがあります。ところが、CodeIgniter2になって構成が大きく変わったため、まともに動作しませんでした。

そこで、分からないながらも、動くレベルまで修正してみました。

確認環境

なにぶん、プログラム初心者が修正したものですので、使用は自己責任にてお願いいたします。

ログインユーザー用データベース設定(MySQL)

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(64) NOT NULL,
  `password` varchar(64) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

/仮にユーザーを登録する/
INSERT INTO users VALUES (1, 'test', MD5('test'));

application/controllers/sample.php

function __construct()
{
    parent::__construct();
    // シンプルログインライブラリを読み込む
    $this->load->library('simplelogin');

    $this->load->library('session');
    $this->load->database();
    $this->load->helper(array('form', 'url'));
    $this->load->library('form_validation');
    $this->output->set_header('Content-Type: text/html; charset=UTF-8');
}

function index()
{
    // セッションでログイン状態を確認
    if($this->session->userdata('logged_in'))
    {
        //User is logged in
        echo 'あなたはログイン中です';
        echo &#039;<hr>&#039;;
        echo anchor(&#039;sample/logout&#039;, &#039;ログアウトする&#039;);
    }
    else
    {
        //User is not logged in
        echo &#039;あなたはログインしていません&#039;;
        echo &#039;<hr>&#039;;
        echo anchor(&#039;sample/login&#039;, &#039;ログインフォームへ&#039;);
    }
}

function login()
{
    // バリデーションルール設定
    $rules[&#039;username&#039;] = "trim|required";
    $rules[&#039;password&#039;] = "trim|required";

    $this->form_validation->set_rules($rules);

    // バリデーションエラー時のフィールド名設定
    // 詳しくは system/language/フォルダ名/validation_lang.php
    $fields[&#039;username&#039;] = &#039;ユーザ名&#039;;
    $fields[&#039;password&#039;] = &#039;パスワード&#039;;

    //$this->form_validation->set_fields($fields);

    // 検証エラーまたは初回アクセス時
    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view(&#039;login&#039;);
    }
    else
    {
        // ユーザ名:test パスワード:testでログインメソッド実行
        $result = $this->simplelogin->login($this->input->post(&#039;username&#039;), $this->input->post(&#039;password&#039;));

        // 結果の検証
        if ($result == TRUE)
        {
            // リダイレクトする
            redirect(&#039;sample/&#039;, &#039;refresh&#039;);
        }
        else
        {
            echo &#039;ユーザ名またはパスワードに誤りがあります。&#039;;
            echo &#039;<hr>&#039;;
            echo anchor(&#039;sample/login&#039;, &#039;もう一度入力する&#039;);
        }
    }
}
function logout()
{
    // ログアウトメソッド実行
    $this->simplelogin->logout();
    echo &#039;ログアウトしました&#039;;
    echo &#039;<hr>&#039;;
    echo anchor(&#039;sample/&#039;, &#039;indexページへ&#039;);
}

}
?>

application/libraries/Simplelogin.php

class Simplelogin {

var $CI;
var $user_table = &#039;users&#039;;

function Simplelogin()
{
    // get_instance does not work well in PHP 4
    // you end up with two instances
    // of the CI object and missing data
    // when you call get_instance in the constructor
    //$this->CI =&amp; get_instance();
}

/**
 * Create a user account
 *
 * @access  public
 * @param   string
 * @param   string
 * @param   bool
 * @return  bool
 */
function create($user = &#039;&#039;, $password = &#039;&#039;, $auto_login = true)
{
    //Put here for PHP 4 users
    $this->CI =&amp; get_instance();

    //Make sure account info was sent
    if ($user == &#039;&#039; OR $password == &#039;&#039;)
    {
        return false;
    }

    //Check against user table
    $this->CI->db->where(&#039;username&#039;, $user);
    $query = $this->CI->db->getwhere($this->user_table);

    if ($query->num_rows()> 0)
    {
        //username already exists
        return false;

    }
    else
    {
        //Encrypt password
        $password = md5($password);

        //Insert account into the database
        $data = array(
                    &#039;username&#039; => $user,
                    &#039;password&#039; => $password
                );
        $this->CI->db->set($data);
        if(!$this->CI->db->insert($this->user_table)) {
            //There was a problem!
            return false;                  
        }
        $user_id = $this->CI->db->insert_id();

        //Automatically login to created account
        if ($auto_login)
        {      
            //Destroy old session
            $this->CI->session->sess_destroy();

            //Create a fresh, brand new session
            $this->CI->session->sess_create();

            //Set session data
            $this->CI->session->set_userdata(array(&#039;id&#039; => $user_id,&#039;username&#039; => $user));

            //Set logged_in to true
            $this->CI->session->set_userdata(array(&#039;logged_in&#039; => true));         

        }

        //Login was successful     
        return true;
    }

}

/**
 * Delete user
 *
 * @access  public
 * @param integer
 * @return  bool
 */
function delete($user_id)
{
    //Put here for PHP 4 users
    $this->CI =&amp; get_instance();

    if(!is_numeric($user_id))
    {
        //There was a problem
        return false;         
    }

    if($this->CI->db->delete($this->user_table, array(&#039;id&#039; => $user_id)))
    {
        //Database call was successful, user is deleted
        return true;
    }
    else
    {
        //There was a problem
        return false;
    }
}

/**
 * Login and sets session variables
 *
 * @access  public
 * @param   string
 * @param   string
 * @return  bool
 */
function login($user = &#039;&#039;, $password = &#039;&#039;)
{
    //Put here for PHP 4 users
    $this->CI =&amp; get_instance();       

    //Make sure login info was sent
    if ($user == &#039;&#039; OR $password == &#039;&#039;)
    {
        return false;
    }

    //Check if already logged in
    if ($this->CI->session->userdata(&#039;username&#039;) == $user)
    {
        //User is already logged in.
        return false;
    }

    //Check against user table
    $this->CI->db->where(&#039;username&#039;, $user);
    $query = $this->CI->db->get_where($this->user_table);

    if ($query->num_rows()> 0)
    {
        $row = $query->row_array();

        //Check against password
        if(md5($password) != $row[&#039;password&#039;])
        {
            return false;
        }

        //Destroy old session
        $this->CI->session->sess_destroy();

        //Create a fresh, brand new session
        $this->CI->session->sess_create();

        //Remove the password field
        unset($row[&#039;password&#039;]);

        //Set session data
        $this->CI->session->set_userdata($row);

        //Set logged_in to true
        $this->CI->session->set_userdata(array(&#039;logged_in&#039; => true));         

        //Login was successful     
        return true;
    }
    else
    {
        //No database result found
        return false;
    }   

}

/**
 * Logout user
 *
 * @access  public
 * @return  void
 */
function logout()
{
    //Put here for PHP 4 users
    $this->CI =&amp; get_instance();       

    //Destroy session
    $this->CI->session->sess_destroy();
}

}
?>

application/views/login.php




シンプルログインフォーム


<?php if ($this->form_validation->error_string):?>
<?php echo $this->form_validation->error_string; ?>
<?php endif;?>

シンプルログインフォーム

<?php echo form_open('sample/login'); ?>

ユーザ名(test)
パスワード(test)

ダウンロード

参考

created by Rinker
¥4,730 (2022/09/29 23:26:30時点 Amazon調べ-詳細)