I'm am very new to CI the MVC model.
I have a simple page which is made of up 3 views. Header, Content and Footer. The content will be unique across the site but header and footer will be the same, no matter what page.
In my header I have a login form. So there will be a login form across the whole site. since it appears on every page which has diff models:
how will or where will I write the script for logging in a user as I don't fancy writing a login script on every model the header is used on...
Maybe another example:
If that's not clear, I try another example. Suppose I have a site. In that I load a view which is a footer in all my pages. and the footer contains a form. Now when I post data using that form, where should that data it go?
Show it go to a dedicated PHP file which handles all the posts from that form, or should it go to the current page' controller?
I hope I was clear. Again I Just started using CI and MVC a day ago. It would be nice if you could guide me.
When i post data using that form, where should that data it go?
You shouldn't write the logic on every page (controller). What you should do is creating a distinct controller (like Accounts
) for managing user logging.
The login form should post the data to accounts/login
URL. but to get back to the previous page, we should store current URL in session as referer
.
To do that, just store uri_string();
in the session on each page you need.
$this->session->set_userdata(array(
'referer' => $this->uri->uri_string()
));
If you don't need to redirect the user to the previous page, ignore it.
The example below indicates how to achieve the goal:
class Accounts extends CI_Controller {
public function login()
{
$config = array(
// Write your validation rules here
);
$this->load->library('form_validation');
$this->form_validation->set_rules($config);
// Check whether form is submitted
if (isset($_POST['submit'])) {
if ($this->form_validation->run() == FALSE) {
$data['login_errors'] = validation_errors();
// Store validation errors in session
// to display on every page needed
$this->session->set_userdata($data);
} else {
// Login process
// Set user detail in session
// Redirect to previous page after login
if ($referer = $this->session->userdata('referer')) {
$this->session->unset_userdata('referer');
} else {
$referer='';
}
redirect(base_url().$referer);
}
}
}
public function logout()
{
// Destroy the session
$this->session->sess_destroy();
redirect(base_url());
}
}