PHP MVC CodeIgniter Laravel Core PHP MORE

How to sign In User using PHP MVC with example


Here is the view file index.php under Login folder, for displaying the form which will be used for Login users data.

views/login/index.php

index.php

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<center>
<div class="floating-box">
<form name="form1" method="post" action="login/run">
<label for="uname">User Name</label>
<input type="text" id="user_name" name="user_name"><br><br>
<label for="pwd">Password</label>
<input type="password" id="password" name="password"><br><br>
<input name="submit" type="submit" id="submit" value="Login"><br>
<p>New User <a href="signup.php">Register Here</a></p>
</center>
</body>
</html>

To Login User data first we have to create a Controller file.

controller/login.php

<?php

class Login extends Controller {

	function __construct() {
		parent::__construct();
		  Session::init();
	}
	
	
	function index() {
	
		$this->view->render('login/index');
	}
	
	function run()
	{
		$this->model->run();
		
	}
	
	
	/* logging out the user */
	function logout()
	{
		Session::destroy();
		header('location: index');
		exit;
	}
}

Here is the model file which we are using for Registering data to database.

The file login_model.php is created under Models folder

models/login_model.php

login_model.php

<?php

class Login_Model extends Model
{
	public function __construct()
	{
		parent::__construct();
		Session::init();
	}

	public function run()
	{
		
		$user_name=$_POST['user_name'];
		$password=md5($_POST['password']);
		
		$res= $this->db->select("SELECT * FROM `register` WHERE username = '".$username."' AND password = '".$password."'");
		$count = count($res);
		
		if ($count > 0) {
			
			Session::init();
			Session::set('role', "user");
			Session::set('loggedIn', true);
			Session::set('user_name', $user_name);
			Session::set('password', $res[0]['password']);
			header('location: '.URL.'login/index');
		} 
		   else {
			Session::set('loggedIn', false);
			header('location: '.URL);
		}
		
		
	}
		
}
Path: localhost/project_folder_name/view_folder_name/view_filenam Example: localhost/mvc/login/index