登录codeigniter

时间:2015-08-17 11:22:42

标签: php codeigniter

我正在尝试使用以下代码登录。这段代码有问题吗?请提供正确的登录代码..

控制器:

public function login() {
    $data = $this->data;
    $email = $this->input->post('email');
    $password = md5($this->input->post('password'));
    $result = $this->user_model->login($email, $password);

    if (count($result) !== 0) {
        $this->session->set_userdata('user_id', $email);
        $seid = $this->session->userdata('user_id');
        if ($seid == '') {
            redirect(site_url());

        } else {
            redirect('home/view');
        }
    } else {
        redirect('home/index');
    }
}

型号:

function login($email, $password) {
    $this->db->where("email", $email);
    $this->db->where("password", $password);
    $query = $this->db->get("user");
    return $query->result_array();
}

5 个答案:

答案 0 :(得分:0)

试试这个......

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>Simple Login with CodeIgniter</title>
 </head>
 <body>
   <h1>Simple Login with CodeIgniter</h1>
   <?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="passowrd" name="password"/>
     <br/>
     <input type="submit" value="Login"/>
   </form>
 </body>
</html>

控制器:

<?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.  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;
   }
 }
}
?>

型号:

<?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;
   }
 }
}
?>

http://www.iluv2code.com/login-with-codeigniter-php.html

答案 1 :(得分:0)

    Sub uniq()
Dim tmp, tmp1, tmp2 As String
Dim banr() As String
Dim banrrng As Range

Dim devtype() As String
Dim devtyperng As Range

Dim devcon() As String
Dim devconrng As Range

Set banrrng = Range("E2:E400") 'change the range to include all cells

   For Each cell In banrrng
      If (cell <> "") And (InStr(tmp, cell) = 0) Then
        tmp = tmp & cell & "|"
      End If
   Next cell


If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)

banr = Split(tmp, "|")

'For i = LBound(banr) To UBound(banr)
'    txt = txt & banr(i) & vbCrLf
'Next i
'MsgBox txt

'*****************************************************************************
'device type range
Set devtyperng = Range("O2:O400") 'change the range to include all cells

   For Each cell In devtyperng
      If (cell <> "") And (InStr(tmp1, cell) = 0) Then
        tmp1 = tmp1 & cell & "|"
      End If
   Next cell

If Len(tmp1) > 0 Then tmp1 = Left(tmp1, Len(tmp1) - 1)

devtype = Split(tmp1, "|")

'For i = LBound(devtype) To UBound(devtype)
'   MsgBox devtype(i)
'Next i

'*****************************************************************************
'device connection range
Set devconrng = Range("P2:P400") 'change the range to include all cells

   For Each cell In devconrng
      If (cell <> "") And (InStr(tmp2, cell) = 0) Then
        tmp2 = tmp2 & cell & "|"
      End If
   Next cell

If Len(tmp2) > 0 Then tmp2 = Left(tmp2, Len(tmp2) - 1)

devcon = Split(tmp2, "|")

'For i = LBound(devcon) To UBound(devcon)
'   MsgBox devcon(i)
'Next i

'**********************************************************************************888888
'counting number of clicks
Dim clkcntR As Range
Set clkcntR = Range("B2:B400")
Dim clkcnt As Single
clkcnt = Application.CountIf(clkcntR, 1)
MsgBox (clkcnt)

'defining the count array across banner, devicetype and deviceconnection

'Getting count array size
Dim cntArrSiz As Integer 'if any error change type to long
cntArrSiz = 1
cntArrSiz = cntArrSiz * (Application.CountA(banr))
cntArrSiz = cntArrSiz * (Application.CountA(devtype))
cntArrSiz = cntArrSiz * (Application.CountA(devcon))
MsgBox (cntArrSiz)

Dim cntArr() As Single 'if any error change type to long
ReDim cntArr(cntArrSiz)

Dim PropArr() As Single 'if any error change type to long
ReDim PropArr(cntArrSiz)

Dim PercArr(), sampSize, rndSize As Integer
ReDim PercArr(cntArrSiz)
sampSize = 25
rndSize = 400

Dim loopCount As Integer ' if any error change type to long
loopCount = 1


For Each cell1 In banr
    For Each cell2 In devtype
        For Each cell3 In devcon

        cntArr(loopCount) = Application.CountIfs(clkcntR, 1, banrrng, cell1, devtyperng, cell2, devconrng, cell3)
        'MsgBox "cntarr" & cntArr(loopCount)
        PropArr(loopCount) = Round((cntArr(loopCount) / clkcnt), 2)
        'MsgBox "PropArr" & PropArr(loopCount)

        PercArr(loopCount) = Round((PropArr(loopCount) * sampSize), 0)
       ' MsgBox "PercArr: " & PercArr(loopCount)

        loopCount = loopCount + 1

        Next
    Next
Next

Randomize 'Initialize Random number seed
Dim MyRows() As Integer    ' Declare dynamic array.
Dim numRows, percRows, nxtRow, nxtRnd, chkRnd, copyRow, percCount As Integer

percCount = 1
    ReDim MyRows(sampSize)
'Create Random numbers and fill array
Dim storeRow As Integer
 storeRow = 1

 Dim evilRng As Range
 Dim cellref As String
Set evilRng = Range("B2:P400")

For Each cell1 In banr
    For Each cell2 In devtype
        For Each cell3 In devcon

     For nxtRow = 1 To PercArr(percCount)
getNew:
'Generate Random number
      nxtRnd = CInt(Int((rndSize * Rnd()) + 1))
      'MsgBox "next random number" & nxtRnd
'Loop through array, checking for Duplicates
       'For chkRnd = 1 To storeRow
'Get new number if Duplicate is found
        If MyRows(chkRnd) = 1 Then GoTo getNew

        cellref = Format(evilRng.Cells(nxtRnd, 5))

        If StrComp(cell1, cellref) <> 0 Then GoTo getNew  ' ***********This is where the error is*******************************8



       'Next
'Add element if Random number is unique
      MyRows(storeRow) = nxtRnd
      storeRow = storeRow + 1
   Next
        percCount = percCount + 1

           Next
       Next
    Next

   storeRow = storeRow - 1

   'Loop through Array, copying rows to Sheet2
     For copyRow = 1 To storeRow
       Worksheets("train").Rows(MyRows(copyRow)).EntireRow.Copy _
        Destination:=Worksheets("Sheet1").Cells(copyRow, 1)
     Next
   End Sub ' code working until sampling

试试这个..希望它可以帮到你

答案 2 :(得分:0)

进行类似的更改:

public function login() {
    $this->load->helper('form');
    $this->load->library('form_validation');

    $this->form_validation->set_rules('email', 'Email', 'required');
    $this->form_validation->set_rules('password', 'Password', 'required');

    // This condition check whether the request is post with valid data or not if it's not a post request than form validation return FALSE
    if ($this->form_validation->run() == FALSE) {

        // This condition check if session id is set or not if session id is set it will redirect you to homepage.
        if (isset($this->session->userdata['user_id'])) {
            redirect('home/view');
        } else {

            //else it will redirect you to login page.
            $this->load->view('login_view');
        }
    } else {

        //if it's a post request with valid data it will validate data in database.
        $email = $this->input->post('email');
        $password = md5($this->input->post('password'));
        $result = $this->user_model->login($email, $password);

        //This condition redirect you to homepage if you entered valid credentials 
        if (count($result) !== 0) {
            $this->session->set_userdata('user_id', $email);
            redirect('home/view');
        } else {

            //This will redirect you to login page with error.
            $this->session->set_flashdata('message', 'Login Fail!!<br>Invalid username or password!!');
            redirect('login');
        }
    }
}

此代码会将您重定向到登录页面,以防它无法获取会话ID,否则会将您重定向到主页。

答案 3 :(得分:0)

<强>模型

function fetchrowlogin($info,$table){
    $this->db->select('*');
    $this->db->where($info);
    $this->db->from($table);
    $query = $this->db->get();
    if($query->num_rows() > 0){
    $row = $query->row_array();
        return $row;
    }
}  

<强>控制器

function login(){
    if(isset($_POST['login'])){
        $log['email'] = $_POST['email'];
        $log['password'] = $_POST['password'];
        $details = $this->User_model->fetchrowlogin($log,'candidate');

        if(count($details)){
            $ids = $details['id'];
            $email = $details['email'];
            $fname = $details['fname'];

            $this->session->set_userdata(array(

                'custid' => $ids,
                'emailid'=> $email,
                'fname'=> $fname,
            ));
            redirect('http://localhost/test27/index.php/welcome/dashboard');
        }else{
            redirect(base_url().'front1');
        }
    }
    $this->load->view('front/login');
}

答案 4 :(得分:0)

创建控制器Login.php

<?php
class Login extends CI_Controller

{
    public function __construct()
    {
        parent::__construct();

        $this->load->model('Common_model');
    }

    public function index()
    {
        $data['title']="Welcome to login page";
        $this->load->view('login',$data);
    }

    public function login()
    {

            $this->load->library('form_validation');
            $this->load->helper('cookie');

            $this->form_validation->set_rules('username', 'username', 'required'); 
            $this->form_validation->set_rules('password', 'password', 'required');


            if ($this->form_validation== FALSE)
            {
              $this->load->view('login');
            }
            else
            {
                $username=$this->input->post('username');
                $pass=$this->Common_model->encrypt_script($this->input->post('password'));
               // print_r($pass);exit;
                $remember=$this->input->post('remember');
                $where=array("email"=>$username , "password"=>$pass);
                //print_r($where);exit;

            if( !$data['res'] = $this->Common_model->select_where('user_master',$where))
            {

                $this->session->set_flashdata('error_message','Invalide username and password');
                // $this->session->keep_flashdata('error_message');
                $error_message=$this->session->flashdata('error_message');

                redirect(base_url().'login','refresh');
                    //echo "error";

            }
            else
            {
                $session_data=array(
                                'username'=>$username
                                );

                $this->session->set_userdata($session_data);

            if($remember != NULL)
            {
                setcookie('username',$username,time()+3600);
            }
                redirect(base_url().'control/display');
            }
        } 
    }

    public function logout()
    {
        $this->session->unset_userdata('username');
        redirect('login/login');
    }
}

创建表单表单登录Login.php

<!DOCTYPE html>
<html lang="en">
    <!-- BEGIN HEAD -->
    <head>

    <body class=" login">
        <!-- BEGIN LOGO -->
        <div class="logo">
            <a href="<?=base_url()?>">
                <img src="<?php echo base_url('assets/pages/img/logo-big.png')?>" alt="" /> </a>
        </div>
            </a>
        </div>
        <!-- END LOGO -->
        <!-- BEGIN LOGIN -->
        <div class="content">
            <!-- BEGIN LOGIN FORM -->
             <form name="login_form" class="login-form" action="<?=base_url()?>login/login" method="post" id="login_form">
                <h3 class="form-title font-green">Sign In</h3>
                <?php
                    if (!empty(form_error('email'))) { ?>
                        <div class="text-center alert alert-danger" id="div_msg">
                            <?php echo '<label class="error-list-color">' . urldecode(form_error('email')) . '</label>';
                            ?> 
                        </div>
                    <?php } ?> 
                <?php     

                    if (!empty($msg)) {
                    ?>
                        <div class="col-sm-12 text-center alert alert-danger" id="div_msg">
                            <?php echo '<label class="error-list-color">' . urldecode($msg) . '</label>';
                            ?> 
                        </div>
                    <?php } ?>
                <div class="form-group">
                    <label class="control-label visible-ie8 visible-ie9">username</label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" value="<?= !empty($_COOKIE['username']) ? htmlentities($_COOKIE['username']) :  set_value('username'); ?>" />

                    <p ><?php echo form_error('email'); ?></p> 
                </div>
                <div class="form-group">
                    <label class="control-label visible-ie8 visible-ie9">Password</label>
                    <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" value="<?= !empty($_COOKIE['password']) ? htmlentities($_COOKIE['password']) :  ''; ?>"/> 
                    <p><?php echo form_error('password'); ?></p>

                </div>
                <div class="form-actions">
                    <button type="submit" class="btn green uppercase">Login</button>
                    <label class="rememberme check">
                        <input type="checkbox" name="remember" value="1" />Remember </label>
                    <a href="javascript:;" id="forget-password" class="forget-password" onclick="show_forget()">Forgot Password?</a>
                </div>

                 <div class="create-account">
                <p>
                    <a href="<?=base_url()?>user_authentication">Login With Facebook</a>
                </p> 
            </div>
            </form>


            <!-- END LOGIN FORM -->
           <!-- BEGIN FORGOT PASSWORD FORM -->
            <form class="forget-form" id="forget_form" action="<?=base_url()?>admin/login/forget_password" method="post" >
                <h3 class="font-green">Forget Password ?</h3>
                <p> Enter your e-mail address below to reset your password. </p>

                <div class="form-group">
                    <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Email" name="forgot_email" />
                    <p><?php echo form_error('forgot_email'); ?></p>
                </div> 

                <div class="form-actions">
                    <button type="button" id="back-btn" onclick="show_login()" class="btn btn-default">Back</button>
                    <button type="submit" class="btn btn-success uppercase pull-right">Submit</button>
                </div>
            </form>
            <!-- END FORGOT PASSWORD FORM -->

        </div>
        <div class="copyright"> 2017 © Facil E-commerce. </div>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
          <script>
            $(document).ready(function() 
            {
                $("#div_msg").fadeOut(4000);

                $('#login_form').validate({
                    rules:{
                        username: {
                            required: true,
                            email: true,
                        },
                        password: {
                            required: true,
                            minlength:5
                        },
                    },
                    messages : {
                        username: {
                            required:"Please enter email address."
                        },
                        password : {
                            required:"Please enter password."
                        }
                    },

                    invalidHandler: function(event, validator) { //display error alert on form submit   

                    },
                    highlight: function(element) { // hightlight error inputs
                        $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                    },
                    success: function(label) {
                        label.closest('.form-group').removeClass('has-error');
                        label.remove();
                    },
                });
                $('#forget_form').validate({
                    rules:{
                        forgot_email: {
                            required: true,
                            email: true
                        },        
                    },
                    messages : {
                        forgot_email: {
                            required:"Please enter email address."
                        },
                    },

                    invalidHandler: function(event, validator) { //display error alert on form submit   

                    },
                    highlight: function(element) { // hightlight error inputs
                        $(element).closest('.form-group').addClass('has-error'); // set error class to the control group
                    },
                    success: function(label) {
                        label.closest('.form-group').removeClass('has-error');
                        label.remove();
                    },
                });
            });
            function show_forget() {
                $('#login-form').hide();
                $('#forget-form').show();
            }
            function show_login() {
               $('#forget-form').hide();
               $('#login-form').show();
            }
        </script>


    </body>

</html>