Login Form in CodeIgniter (without MySQL)
Here, we'll make a simple login page with the help of session.
Go to file autoload.php in application/config/autoload.php
Set session in library and helper.
Create controller page Login.php in application/controllers folder.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function index()
{
$this->load->view('login_view');
}
public function process()
{
$user = $this->input->post('user');
$pass = $this->input->post('pass');
if ($user=='juhi' && $pass=='123')
{
//declaring session
$this->session->set_userdata(array('user'=>$user));
$this->load->view('welcome_view');
}
else{
$data['error'] = 'Your Account is Invalid';
$this->load->view('login_view', $data);
}
}
public function logout()
{
//removing session
$this->session->unset_userdata('user');
redirect("Login");
}
}
?>
Look at the above snapshot, we have created a session for a single user with Username juhi and Password 123. For a valid login and logout we will use this username and password.
Create view page login_view.php in application/views folder.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php echo isset($error) ? $error : ''; ?>
<form method="post" action="<?php echo site_url('Login/process'); ?>">
<table cellpadding="2" cellspacing="2">
<tr>
<td><th>Username:</th></td>
<td><input type="text" name="user"></td>
</tr>
<tr>
<td><th>Password:</th></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Create view page welcome_view.php in application/views folder to show the successful login message.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Welcome <?php echo $this->session->userdata('user'); ?>
<br>
<?php echo anchor('Login/logout', 'Logout'); ?>
</body>
</html>
Output
Type URL localhost/login/index.php/Login
Now on entering wrong information we'll be see unsuccessful message which we have set in login_view page in else part.
Now on entering right information, we'll see welvome_view.php message.
Click on Logout, we'll be directed to Login page.