After following the CodeIgniter's excellent documentation I have a very simple news article system setup which allows anyone to post an article if they go to news/create. I am now trying to implement a simple log in solution which will only allow logged in users to post articles, I have followed this tutorial (http://www.iluv2code.com/login-with-codeigniter-php.html) and have it working as it shown in the tutorial however the issues arise when instead of getting the user to land on the private page once they have logged in I want them to land on news/create.
My attempts to get this working have allowed me to get the user to land on the page but the page then fails to render properly leaving the article submission form not existent. Here is the code which I believe is causing the issue (mainly the 'Create' function):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
public function index()
{
$data['news'] = $this->news_model->get_news();
$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');
}
public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
public function create()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data1['username'] = $session_data['username'];
$this->load->view('news/create', $data1);
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('templates/header', $data);
$this->load->view('news/success');
$this->load->view('templates/footer');
}
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('news', 'refresh');
}
}
For those whose comments asking about the session, there is a separate controller creating that session (as seen below). This is functioning fine though as on the 'private page' which only logged in users can access it currently displays the username however it fails to render any of the create function after the initial 'is the user logged in or not'.
<?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('news/create', '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;
}
}
}
?>
Any guidance or help would be greatly appreciated.
After sometime of going through this code I finally arrived at the issue and will post the solution here incase anyone else comes across a similar problem and they can use this as reference.
I was trying to load a view in the initial check to see whether a user was logged on, deleting this line allowed the rest of the solution function as it should.
public function create()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data1['username'] = $session_data['username'];
$this->load->view('news/create', $data1); ----- LINE IN QUESTION
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
Related
I want to create a profile view for the user that is currently logged in. I created a session_data array for when you log in that only contains their username. How would I retrieve the other values from the row depending on who is logged in? Do I have to add all that information to the session_data array?
I have the values first_name, last_name, & date_joined that I want to display alongside username.
Login Controller:
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('templates/header');
$this->load->view('login');
$this->load->view('templates/footer');
}
function login_validation()
{
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run())
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('login_model');
if ($this->login_model->can_login($username, $password))
{
$session_data = array(
'username' => $username
);
$this->session->set_userdata($session_data);
redirect('home');
}
else {
$this->session->set_flashdata('error', 'Invalid Username and Password');
redirect('login');
}
}
else {
$this->index();
}
}
function enter()
{
if ($this->session->userdata('username') != '') {
echo "Welcome " . $this->session->userdata('username');
echo 'Logout';
}
else {
redirect('login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect('login');
}
}
User View:
<h4><?php echo $_SESSION['username']; ?></h4>
You'll need a method in login_model that retrieves the username info based on the username you send to it.
Something like this:
function get_user($username)
{
$this->db->select(*);
$this->db->from('users');
$this->db->where('username', $username);
$query = $this->db->get();
if ($this->db->affected_rows())
{
return $query->row();
}
}
On the other hand, I recommend you to use an existing authentication library.
Ion Auth is pretty good.
Good luck!
how to echo session data to view profile using codeigniter or help me to pass id with session to get user profile
controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller
{
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->database();
$this->load->library('session');
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('User_Model');
$this->load->helper('url');
$this->load->library('parser');
}
public function index()
{
$this->load->view('login');
}
public function register()
{
$this->load->view('Register');
}
public function Save()
{
$this->form_validation->set_rules('email', 'email', 'required');
if ($this->form_validation->run() == false)
{
echo 'Please enter correct email.';
exit;
}
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == false)
{
echo 'Please enter password.';
exit;
}
if ($this->form_validation->run() == true)
{
$email = $this->input->post('email');
$password = md5(trim($this->input->post('password')));
$res = $this->User_Model->Save($email,$password);
exit;
}
}
public function Login()
{
$this->form_validation->set_rules('email', 'email', 'required');
if ($this->form_validation->run() == false)
{
echo 'Please enter correct email.';
exit;
}
$this->form_validation->set_rules('password', 'password', 'required');
if ($this->form_validation->run() == false)
{
echo 'Please enter password.';
exit;
}
if ($this->form_validation->run() == true)
{
$email = $this->input->post('email');
$password = md5(trim($this->input->post('password')));
$res = $this->User_Model->login($email,$password);
echo $res;
exit;
}
}
public function dashboard()
{
$this->load->view('welcome');
}
public function logout()
{
$this->session->sess_destroy();
redirect(base_url().'index.php/User/');
}
}
?>
Using raw php, you check session data using $_SESSION
Inside codeigniter, you can check session data using print_r($this->session->all_userdata());
Codeigniter follows the MVC design model this means that data is first generated by a module is passed then to a controller and finally the controller inflates data into a certain view.
Load a view from Controller
$this->load->view('view_name', $data, true/false);
in this example you see how to load a view passing to it some data.
So assuming you have a view in your view folder called show_session.php
we can create the following method in the controller to show the session data you want the user to be able to see.
public function index()
{
$data['info'] = $this->session->all_userdata();
$this->load->view('show_session',$data);
}
Create the view
In case you don't have that view you create it with the following contents:
<!DOCTYPE html>
<html>
<head>
<title>Simple data</title>
</head>
<body>
<?php
foreach ($info as $key => $value) {
echo $key." => ".$value."<br>";
}
?>
</body>
</html>
finally save it into /application/views folder.
Credit and more info: here
I want to connect from one controller in one module to another controller in another module. I want to go from my login module to my dashboard module and use a function inside the dashboard module. Just basically switch from my login module to my dashboard module. Here is my login controllers and my dashboard controller.
class Login extends MX_Controller {
function index()
{
$this->load->view('includes/header');
$this->load->view('login_form');
$this->load->view('includes/footer');
}
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('login/site/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
function signup()
{
//$data['main_content'] = 'signup_form';
//$this->load->view('includes/template', $data);
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_if_email_exists');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]|max_length[15]|callback_check_if_username_exists');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE) // didn't validate
{
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->create_member())
{
$data['account created'] = 'Your account has been created. <br /> <br /> You may now login';
$this->load->view('includes/header');
$this->load->view('signup_successful', $data);
$this->load->view('includes/footer');
}
else
{
$this->load->view('includes/header');
$this->load->view('signup_form');
$this->load->view('includes/footer');
}
}
}
function check_if_username_exists($requested_username)
{
$this->load->model('membership_model');
$username_available = $this->membership_model->check_if_username_exists($requested_username);
if ($username_available)
{
return TRUE;
}else{
return FALSE;
}
}
function check_if_email_exists($requested_email)
{
$this->load->model('membership_model');
$email_available= $this->membership_model->check_if_email_exists($requested_email);
if ($email_available)
{
return TRUE;
}else{
return FALSE;
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
my second login controller
class Site extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->is_logged_in();
$this->lang->load('login/login/', 'english');
}
function members_area()
{
$this->load->view('logged_in_area');
//$this->load->module('dashboard/dashboard');
//$this->load->view('home');
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true)
{
echo 'You don\'t have permission to access this page. Login';
die();
//$this->load->view('login_form');
}
}
}
the controller in my dashboard module has a function called home I am trying to connect to and use. And the home function of the dashboard has a connection to another module but I cannot get the connection from login to dashboard to work. Also the way my login works I need to connect to the dashboard module through my members_area function. All help greatly appreciated.
Assuming you're using this library
From controller you can use Modules::load or $this->load-module
$moduleInstance = $this->load->module('yourmodule');
// or
$moduleInstance = Modules::load('yourmodule');
// Now you can call any public module controller method
$moduleInstance->somePublicMethod($arg1, $argn);
// you can also use $this->yourmodule as a model instance
Hope this helps
I have codeigniter installed on my localhost
The main.php controller is
class Main extends CI_Controller {
public function index()
{
$this -> login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
}
The login is working page is coming,but after I fill the username and password,should take me to login/main/login_validation and from there the function login_validation() should either redirect to main/members or show me the login page.But what happens is when I submit the form,the object not found error is coming.Can anyone help me out?
form is
form_open('main/login_validation');
To answer what I think your question is getting at, you're using the form_validation class wrong. You should be testing whether or not the form_validation->run() is TRUE (all fields passed validation) or FALSE (there was an error in one or more of the inputs). Structure you code like such:
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('login');
}
else
{
redirect('main/members');
}
}
This is covered in the CodeIgniter documentation here.
in your controller ..you could try this..
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login');
}
else
{
$this->check_database();
//redirect('home');
}
}
function check_database()
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
$password = $this->input->post('password');
//query the database
$query_result = $this->model_login->login($username, $password);
if($query_result)
{
$this->load->view('main/members');
}
else
{
redirect('login');
}
}
in model
function login($username,$password){
$query = $this->db->query("SELECT * FROM `login` WHERE `username`= '".$username."' AND
password='".$password."' LIMIT 1");
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}
I have implemented a basic login system using CodeIgniter. I am using the sessions library to control access to a members only section. I can log in and view this area no problem. However when I delete my cookies and refresh the members only section page I can still see the content. I am not displaying a login message to the user.
I don't know why this is happening. Any ideas?
This is my Site.php controller
class Site extends CI_Controller{
function _construct(){
parent::_construct();
$this->is_logged_in();
}
function members_area(){
$this->load->view('members_area');
}
function is_logged_in(){
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true){
echo 'You need to login to access this page. Login';
die();
}
}
}
This is my login.php Controller
class Login extends CI_Controller{
function index(){
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials(){
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query){//if credentials validated
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site/members_area');
}
else{//If not validated re load login form
$this->index();
}
}
function signup(){
$data['main_content'] = 'signup_form';
$this->load->view('includes/template', $data);
}
function create_member(){
$this->load->library('form_validation');
//field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
if($this->form_validation->run() == FALSE){
$this->signup();
}
else{
//create a new row in db
$this->load->model('membership_model');
if($query = $this->membership_model->create_member()){
//Info entered
$data['main_content'] = 'signup_successful';
$this->load->view('includes/template', $data);
}
else{
$this->load->view('signup_form');
}
}
}
}
This is the code that should be executed if a session does not exist. It is found in the site.php file.
if(!isset($is_logged_in) || $is_logged_in != true){
echo 'You need to login to access this page. Login';
die();
Any help is much appreciated!
Looks like your constructor isn't being called.
Perhaps it is because it needs two underscores, not 1 :)
function __construct(){
parent::__construct();
$this->is_logged_in();
}