PHP MVC CodeIgniter Laravel Core PHP MORE

How to Change Password using PHP MVC with example


In this example we using Models, Views, Controller Structure for Changing password in the database.

To change password in the database first we have to create a view page.

views/changepassword/changepassword.php

<!DOCTYPE html>
<html>
	<body>
		 <form action="<?php echo URL; ?>changepassword/submit_changepassword" method="post">
	                 <input type="text" name="oldpassword" id="oldpassword" placeholder="Enter Your Old Password"><br>
	     		 <input type="text" name="newpassword" id="newpassword" placeholder="Enter Your New Password"><br>
	      		 <input type="text" name="confirmpassword" id="confirmpassword" placeholder="Enter Confirm Password"><br>
	     		 <span id='message'></span>
	   		 <input type="hidden" value="<?php echo Session::get('id'); ?>" name="id">
		   	 <button type="submit" value="submit" name="submit" style="background-color:#008000">Submit</button>
	 	 </form>
       
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#newpassword, #confirmpassword').on('keyup', function () {
 	 if ($('#newpassword').val() == $('#confirmpassword').val()) {
    		$('#message').html('Matching').css('color', 'green');
  	 } else 
   		 $('#message').html('Not Matching').css('color', 'red');
	});
</script>

Here is the model file which we are using for Change Password.

The file changepassword_model.php is created under Models folder

models/changepassword_model.php

<?php

class Changepassword_model extends Model
{
	public function __construct()
	{
		parent::__construct();
	}
	public function changepassword($data,$arg)
	{
		 $this->db->update('register', $data,"`id` = $arg");
			
	}
	
	public function error($msg)
	{
		return '<div id="error">'.$msg.'</div>';
	}
}
?>

Here is the Controller file changepassword.php which inside controllers folder

controllers/changepassword.php

<?php

class Changepassword extends Controller
{
	public function __construct()
	{
		parent::__construct();
		Session::init();
	}
		function changepassword() {
				
			$this->view->render('changepassword/changepassword');
		}
		function submit_changepassword() {
		       if(md5($_POST['oldpassword'])==Session::get('password')){
				$arg=$_POST['id'];
				$data=array(
					'password'=>md5($_POST['confirmpassword'])
					   );
		
		 $this->model->changepassword($data,$arg);
		 $this->view->msg = $this->model->error("Your Password is updated Successfully.");
		
			 }
			 else{
				$this->view->msg = $this->model->error("You Entered an Invalid Password.");
				
			}
			
		}
}
?>
Path: localhost/project_folder_name/view_folder_name/view_filename Example: localhost/mvc/changepassword/changepassword