2012-02-04 116 views
1
<?php echo validation_errors(); ?> 
<?php echo form_open('verifylogin'); ?> 
    <label for="username">Username:</label> 
    <input type="text" size="20" id="username" name="username"/> 
    <br/> 
    <label for="password">Password:</label> 
    <input type="password" size="20" id="password" name="password"/> 
    <br/> 
    <input type="submit" value="Login"/> 
</form> 

我使用該代碼來驗證填寫的表單,但瀏覽器在我提交後沒有顯示任何內容。我的瀏覽器的URL是停留在http://example.com/index.php/verifylogincodeigniter中的表單驗證

verifylogin.php這樣定義

<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); 

class VerifyLogin extends CI_Controller { 

function __construct() 
{ 
    parent::__construct(); 
    $this->load->model('user','',TRUE); 
} 

function index() 
{ 
    //This method will have the credentials validation 
    $this->load->library('form_validation'); 

    $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); 
    $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); 

    if($this->form_validation->run() == FALSE) 
    { 
    //Field validation failed.&nbsp; 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.&nbsp; 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; 
    } 
} 
} 
?> 
+0

代碼看起來確定。你正在加載會話類嗎?一個註釋:將整個登錄部分放在驗證方法中看起來「很奇怪」,驗證應該只是做驗證。您應該將整個login()方法放在該塊之外,以便在驗證通過時運行; – 2012-02-04 09:37:20

回答

1
class Auth extends CI_Controller{ 

    public function __construct(){parent::__construct();} 
    /** 
    * Login Form 
    * 
    * $route['login'] = 'auth/login_form'; 
    * 
    */ 
    public function login_form(){ 
     $this->load->view('login_form'); 
    } 
    /** 
    * Login Validation 
    * 
    * $route['login/check'] = 'auth/login_check'; 
    * Point your form to login/check 
    */ 
    public function login_check() 
    { 
     if($this->form_validation->run() == TRUE) 
     { 
      //form validates... 
     }else 
     { 
      //no redirect! just show for again! 
      $this->login_form(); 
     } 
    } 
}