我按照教程使用 CodeIgniter 创建一个简单的登录(我使用的版本是最后一个),但是当我插入用户名和密码时,我只得到“无效的用户名或密码”如果我错过了两者之一,那就太好了,但两者都是正确的。该数据库是在 PHPmyAdmin 中创建的(我使用 WAMP,用户为 root,没有密码),表名为 users,我创建了两个不同的用户。如果有必要我也可以放其他文件的代码(database.php 等)。所以,我不明白我错了什么,这是 Controller :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->helper('url');
}
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
}
else
{
//Go to private area
redirect('home', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
?>
这是User.php
<?php
Class User extends CI_Model
{
function login($username, $password)
{
$this -> db -> select('id, username, password');
$this -> db -> from('users');
$this -> db -> where('username', $username);
$this -> db -> where('password', MD5($password));
$this -> db -> limit(1);
$query = $this -> db -> get();
if($query -> num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
}
?>
最佳答案
根据您的意见:
Yes,It returns this: Array ( [0] => stdClass Object ( [id] => 1 [username] => fabio [password] => fabio ) ) . Sorry, before I deleted that print , I did not understand what you wanted to do. – user5913892 9 mins ago
您的数据库中的 MD5()
中没有密码。为此你需要使用这个:
$this -> db -> select('id, username, password');
$this -> db -> from('users');
$this -> db -> where('username', $username);
$this -> db -> where('password', $password);
$this -> db -> limit(1);
对密码等 secret 数据使用加密是一种很好的做法,我建议您将密码插入 MD5()
而不是在登录时使用 MD5()
.
关于php - Codeigniter 3 中的用户名或密码无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604753/