简体   繁体   English

用户注册CodeIgniter

[英]User registration with CodeIgniter

I'm trying to build a registration system with CodeIgniter. 我正在尝试使用CodeIgniter构建注册系统。 I have a controller called Register with the following code: 我有一个名为Register的控制器,代码如下:

class Register extends CI_Controller {
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
        $this->form_validation->set_rules('email', 'email', 'required|valid_email|trim');
        $this->form_validation->set_rules('artist', 'artist', 'max_length[32]|trim');
        $this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|trim');
        $this->load->view('header');
        if(!$this->form_validation->run())
        {
            $this->load->view('register_form');
        }
        else
        {
            $this->load->view('register_done');
        }
        $this->load->view('footer');
    }
}

So far so good. 到现在为止还挺好。 If I go to the register page I get the registration form displayed. 如果我进入注册页面,我会看到注册表格。 If I send the form and it passes the form validation checks, I get the success page, if the form has errors, I get the form back with some error messages. 如果我发送表单并通过表单验证检查,我会获得成功页面,如果表单有错误,我会返回表单并附带一些错误消息。

Now what I want to do is the database stuff. 现在我想做的是数据库的东西。 I have some idea of how I can get the POST values from the registration form into my database, but no clue how I can check if a username or email already exists, and if so, display that error on the registration form. 我知道如何从注册表单中获取POST值到我的数据库,但不知道如何检查用户名或电子邮件是否已经存在,如果是,则在注册表单上显示该错误。 Here's my registration form view: 这是我的注册表格视图:

<?php $this->load->helper('form'); ?>
<?php echo form_open('register'); ?>
    <ul id="register">
        <ul>
            <h3>Account information</h3>
            <li>
                <label for="username">Choose a username</label>
                <input type="text" name="username" value="<?php echo set_value('username'); ?>" />
                <span class="desc">The name you'd like to be known by</span>
                <?php echo form_error('username'); ?>
            </li>
            <li>
                <label for="password">Pick a password</label>
                <input type="password" name="password" />
                <span class="desc">The best passwords are random and more than 6 characters long</span>
                <?php echo form_error('password'); ?>
            </li>
            <li>
                <label for="email">Enter your valid email address</label>
                <input type="text" name="email" value="<?php echo set_value('email'); ?>" />
                <span class="desc">We'll send you an activation email</span>
                <?php echo form_error('email'); ?>
            </li>
        </ul>
        <ul>
            <h3>About you</h3>
            <li>
                <label for="band">Who's your favorite artist?</label>
                <input type="text" name="artist" value="<?php echo set_value('artist'); ?>" />
                <span class="desc">Don't put Lady GaGa.</span>
                <?php echo form_error('artist'); ?>
            </li>
        </ul>
        <ul>
            <h3>Security question</h3>
            <li>
                <label for="captcha">Enter the letters you see in the image</label>
                <?php $this->load->helper('captcha');
                $cap = create_captcha(array('img_path' => './captcha/', 'img_url' => 'http://localhost/captcha/', 'img_width' => 200, 'img_height' => 30));
                $data = array('captcha_time' => $cap['time'], 'ip_address' => $this->input->ip_address(), 'word' => $cap['word']);
                $query = $this->db->insert_string('captcha', $data);
                $this->db->query($query);
                echo $cap['image']; ?>
                <input type="text" name="captcha" />
                <?php echo form_error('captcha'); ?>
            </li>
        </ul>
        <ul>
            <h3 class="submit">
                <input type="submit" value="Register" />
            </h3>
        </ul>
    </ul>
<?php echo form_close(); ?>

As you can see, I'm taking advantage of the form_error() function of CI to display form errors right under the field, and I would like the "username already exists" error to also be displayed under the username field. 正如您所看到的,我正在利用CI的form_error()函数在字段下显示表单错误,我希望“用户名已存在”错误也会显示在用户名字段下。

Can anyone provide some help? 有谁可以提供一些帮助? Even a nudge in the right direction? 即使是正确方向的推动?

Thanks! 谢谢!

I would strongly urge you to think about using another library that already does this very well: TankAuth . 我强烈建议您考虑使用已经做得非常好的另一个库: TankAuth TankAuth is easily modifiable and offers email confirmation , very secure password hashing , a solid database schema , and very clean code . TankAuth易于修改,提供电子邮件确认 ,非常安全的密码哈希可靠的数据库架构和非常干净的代码

There's no reason to reinvent the wheel, especially when it comes to something that's very hard to get right like user authentication. 没有理由重新发明轮子,特别是当涉及到像用户身份验证这样很难做到的事情时。

EDIT: 编辑:

For example, here's everything TankAuth provides security-wise that you'd have to code yourself (if you cared about security) - how much time would that take? 例如,这里的所有事情都是TankAuth提供安全性的,你必须自己编码(如果你关心安全性) - 需要花多少时间?

Using phpass library for password hashing (instead of unsafe md5).
Counting login attempt for bruteforce preventing (optional). Failed login attempts determined by IP and by username.
Logging last login IP-address and time (optional).
CAPTCHA for registration and repetitive login attempt (optional).
Unactivated accounts and forgotten password requests auto-expire.

You need to create a model for your controller. 您需要为控制器创建模型
Your model would look like this: 你的模型看起来像这样:

class Register_model extends CI_Model {
    function register_user()
    {
        $data['username'] = $this->input->post('username');
        $data['password'] = sha1($this->input->post('password'));
        ... (your other post data) ...
        $this->db->insert('users', $data);
    }
}

In your controller you will call the model this way: 在您的控制器中,您将以这种方式调用模型:

$this->load->model('Register_model');

and the method goes here: 方法在这里:

else
{
    $this->Register_model->register_user(); 
    $this->load->view('register_done');
}

If you want to check if the username is available, you simply put SELECT query on the first lines of the register_user() method (function). 如果要检查用户名是否可用,只需将SELECT查询放在register_user()方法(函数)的第一行。

To do the check you should have functions in your model that can look up those types of things for you: 要进行检查,您应该在模型中具有可以为您查找这些类型的东西的功能:

class Model{
    function getUserByEmail($email);
    function getUserByUsername($username);
    ...
}        

Then in your controller you can call these methods 然后在您的控制器中,您可以调用这些方法

...
$result = $model->getUserByEmail($_POST['email']); // You'll need to sanitize your POST
if(count($result) > 0){
    // Sent error about email already existing and flag to not insert/update user
}
...

The easiest solution in CodeIgniter is to use a callback function as one of the rules in your form validation. CodeIgniter中最简单的解决方案是使用回调函数作为表单验证中的规则之一。 I've used this method myself to check the username and e-mail. 我自己用这个方法检查用户名和电子邮件。

Here's the docs for it. 这是它的文档

defined('BASEPATH') OR exit('No direct script access allowed'); 已定义('BASEPATH')或退出('不允许直接访问脚本');

class User extends CI_Controller { class User扩展CI_Controller {

public function __construct() {

    parent::__construct();

    $this->load->helper('form');

    // Load session library
    $this->load->library('session');

    // Load database
    $this->load->model('User_model');

}

public function index()
    {

        $this->load->view('index');

    }
    public function project()
    {
          $this->data['posts'] = $this->User_model->getPosts(); // calling Post model method getPosts()
            $this->load->view('tables', $this->data);

            // $this->load->aview('project');
    }

    public function get_project()
    {
        $this->User_model->get_project($data);
    }
    public  function signin()
    {

        $data = array(
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password')
        );
        $this->User_model->signin($data);
    }

    public function logout()
    {
        $this->session->unset_userdata($_SESSION['email']);
        // $this->session->sess_destroy();
        redirect('User');
    }
    public function signup()
    {

     $data = array(
            'name' => $this->input->post('name'),
            'phone' => $this->input->post('phone'),
            'email' => $this->input->post('email'),
            'password' => $this->input->post('password')
        );

     if($this->User_model->signup($data))
     {

        echo "no insert";
     }
     else
     {

        $this->load->view('index', $data);
     }

}
}
<?php

Class User_model extends CI_Model {

    function __construct() {
    parent::__construct();
    $this->load->library('session');


    }

    public function signup($data)
    {

        $this->db->insert('user_signup',$data);

    }

    public function getPosts()
     {
              $this->db->select("*"); 
              $this->db->from('user_data');
              $query = $this->db->get();
              return $query->result();
    }



    public function signin($data)
    {
            $this->db->where('email',$data['email']);
            $this->db->where('password',$data['password']);
            $query=$this->db->get('user_signup');
            if($query->num_rows()==1){

                $_SESSION['email'] = $data['email'];

                $this->load->view('popup',$data);

                return true;
    }
    else{
            echo "no";
            return false;
    }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM