我會用PHP password_hash()
在您的數據庫密碼列varchar 255
public function createUser() {
$options = [
'cost' => 12,
];
$new_password = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'username' => $this->input->post('username'),
'password' => $new_password
);
$this->db->set($data);
$this->db->insert('user');
}
上例的輸出類似於:
$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K
和PHP password_verify()
然後,你需要做的是
型號Guide
文件名:Login_model.php
<?php
class Login_model extends CI_Model {
public function getUser() {
if ($this->verify()) {
$this->db->select('*');
$this->db->from('user');
$this->db->where('username', $this->input->post('username'));
if ($query->num_rows() > 0) {
return $query->row();
} else {
return false;
}
}
}
public function verify() {
$hashed = $this->getHash();
$password = $this->input->post('password');
if (password_verify($password, $hashed)) {
return true;
} else {
return false;
}
}
public function getHash() {
$this->db->select('*');
$this->db->from('user');
$this->db->where('username', $this->input->post('username'));
if ($query->num_rows() > 0) {
return $query->row()->password;
} else {
return false;
}
}
}
控制器Guide
文件名:login.php中
<?php
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->model('login_model');
}
public function index() {
$data['title'] = 'Login';
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_verify');
if ($this->form_validation->run() == false) {
$this->load->view('header_view', $data);
$this->load->view('login_view', $data);
$this->load->view('footer_view', $data);
} else {
$userdata = $this->login_model->getUser();
$data = array(
'user_id' => $userdata->user_id
);
// You can set your session userdata
redirect('success');
}
}
public function verify() {
if ($this->login_model->verify()) {
return true;
} else {
$this->form_validation->set_message('verify', 'Opps something gone wrong!');
return false;
}
}
}
注意:不要爲去設置配置您的BASE_URL .php根據需要在CI3版本中這樣做
您應該訪問t他的第一個 http://stackoverflow.com/help/how-to-ask – Dave
@Krystian Niko Liris我有一個答案,希望它有幫助。 – user4419336