CodeIgniter routing issue, advice how to do it - codeigniter

I'm not CI programmer, just trying to learn it. Maybe this is wrong approach, please advice.
my controller(not in sub directory) :
class Users extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index($msg = NULL) {
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function process_logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}
And a route for login :
$route['user/login'] = 'users/index';
Problem is when I wanna logout, it shows me 404 because I do not have it in my route :
$route['user/process_logout'] = 'users/process_logout';
and in my view I put logout
When I add that, it works, and that is stuppid to add a route for everything. What I'm I doing wrong, please advice.
Thank you

Don't know why you are trying to implement login feature in index() function. However since you said you are learning CI I'm telling something about _remap() function.
Before that. You can try the following routing:
$route['user/:any'] = 'users/$1';
$route['user/login'] = 'users/index';
If you want to take value immediately after controller segment you need to use _remap() function and this function may be solve your routing problem, i mean you don't need to set routing. Lets implement your code controller 'users' using _remap() function.
class Users extends CI_Controller {
private $sections = array('login', 'logout');
function __construct() {
parent::__construct();
}
public function _remap($method)
{
$section = $this->uri->segment(2);
if(in_array($section, $this->sections))
call_user_func_array(array($this, '_'.$section), array());
else show_404(); // Showing 404 error
}
private function _login()
{
$msg = $this->uri->segment(3);
$this->load->helper(array('form'));
$data['msg'] = $msg;
$this->load->view('user/login' , $data);
}
public function _logout() {
$this->session->sess_destroy();
redirect(base_url());
}
}

Related

Apply Middleware auth to all routes except `editPostJob/id` in Laravel

I am trying to apply auth middleware to all routes except "editPostJob" route but it didnt work as there is an id in url(http://127.0.0.1:8000/editPostJob/1).
Everytime i tried to go to that link it redirects me to login page.
in controller I tried:
public function __construct()
{
$this->middleware('auth')->except(['index', 'confirm','editPostJob']);
}
but it didnt work.
Any idea what should i do ?
thanks for any help.
I was able to solve it by doing:
public function __construct()
{
$this->middleware('auth')->except(['index', 'confirm', 'yourMethod']);
}
public function yourMethod(Request $request) //select statement
{
if (\Auth::check() == false) {
$is_read = "true";
} else {
$is_read = strip_tags($this->isLoggerOwnerOfPost($request->id));
}
$jobs = DB::table('jobs')->where('job_id', $request->id)->get();
return view('editPostJob', compact('jobs'))->with('is_read', $is_read);
}
Thanks Anurat !

URL change issue after form post in Codeigniter

how can i manage url in address bar after posting a form or after loading a page after submission.
Is it possible to manage with routing ?
<?php
public function index(){
$this->load->view('login');
}
public function login_process(){
....... code......
if($login==true){
$this->load->view('dashboard'); // Url is not changing but view is loaded
}else{
$this->load->view('login');
}
}
?>
Hope this will help you :
Use redirect() method from url helper , make sure you load it in controller or in autoload.php
public function login_process()
{
....... code......
if($login === TRUE)
{
redirect('controller_name/dashboard','refresh');
/*$this->load->view('dashboard'); */
}
else
{
redirect('controller_name/index','refresh');
/*$this->load->view('login');*/
}
}
For more :https://www.codeigniter.com/user_guide/helpers/url_helper.html#redirect
You should create another method called dashboard and you should redirect to it like following
class Example_Controller extends CI_Controller {
public function index(){
$this->load->view('login');
}
public function dashboard(){
$this->load->view('dashboard');
}
public function login_process(){
// Your Code
redirect('Example_Controller/' . (($login==true) ? 'dashboard' : 'index'));
}
}
replace Example_Controller with your controller name.
and add following lines in routes.php
$route['login'] = 'Example_Controller/index';
$route['dashboard'] = 'Example_Controller/dashboard';

Codeigniter & HMVC - Callback not working

I've pretty much gone through a lot of link and solutions provided here and other locations, but I am just not able to solve the callback issue that I am facing. I'm using Codeigniter with HMVC the code is below.
The following code is from My_Form_validation.php:
class MY_Form_validation extends CI_Form_validation {
function run($module = '', $group = ''){
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
Below if the Callback function :
public function _unique_email($str) {
// Check if user already exists
// Process only for current user
$id = $this->uri->segment(4);
$this->db->where('email', $this->input->post('email'));
!$id || $this->db->where('id !=', $id);
$user = $this->mdl_admin_users->get();
if (count($user)) {
$this->form_validation->set_message('_unique_email', 'User already exists. Please check %s.');
return FALSE;
}
return TRUE;
}
and the function :
public function user_edit($id = NULL) {
// Fetch a user or set a new one
if ($id) {
$data['user'] = $this->mdl_admin_users->get($id);
count($data['user']) || $data['errors'][] = 'User could not be found';
}
else {
$data['user'] = $this->mdl_admin_users->get_new();
}
// setup the form
$rules = $this->mdl_admin_users->rules_admin;
$id || $rules['password'] = '|required';
$this->form_validation->set_rules($rules);
//process the form
if ($this->form_validation->run($this) == TRUE) {
$data = $this->mdl_admin_users->array_from_post(array('firstname', 'lastname', 'email', 'password'));
$data['password'] = $this->mdl_admin_users->hash($data['password']);
$this->mdl_admin_users->save($data, $id);
redirect('admin/user');
}
// Load the view
$data['title'] = 'Edit Users';
$data['module'] = 'admin';
$data['header_file'] = 'header_admin';
$data['nav_file'] = 'nav_admin';
$data['view_file'] = 'edit_users';
$data['footer_file'] = 'footer_admin';
echo Modules::run('template/base_template', $data);
}
Would be a great help if someone could point me at the right direction to resolve the issue. Thanks in advance
Naveen
According to wiredesignz,
When using form validation with MX you will need to extend the CI_Form_validation class as shown below,
/** application/libraries/MY_Form_validation **/
class MY_Form_validation extends CI_Form_validation
{
public $CI;
}
before assigning the current controller as the $CI variable to the form_validation library. This will allow your callback methods to function properly.
class Xyz extends MX_Controller
{
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->form_validation->CI =& $this;
}
}
This will remove HMVC related callback problem without any changes to your code.
First of you are missing in the rules
$rules['email'] = 'required|callback__uniqueemail';
Also call back function should be not like this callback__unique_email for some reason I found codeigniter call back not like extra gap this better callback__uniqueemail
If private do not work make public function removing underscore
public function uniqueemail() // no need $str
When make public do not for get to remove extra underscore from here callback_uniqueemail
Another thing with echo Modules run best to be loaded from view only.
In your controller replace echo Modules run with $this->load->view();
You need to add $this->form_validation->run($this) add $this to run after create library below.
And Create a new library
<?php
class MY_Form_validation extends CI_Form_validation {
function run($module = '', $group = '') {
(is_object($module)) AND $this->CI = &$module;
return parent::run($group);
}
}
Tutorial Best https://www.youtube.com/watch?v=8fy8E_C5_qQ

Check for Sessions in Controller _constructor

I am new to Codeigniter and still trying to understand some basics.
I am building a registration/login system. everything good for now.
I am creating a controller to show the user info. Before that I want to check if the session existis and if user is logged in, if not I want to redirect to the site root.
class Myprofile extends CI_Controller {
function __construct()
{
$user_data = $this->session->userdata('user_data');
$user_data['logged_in'] = isset($user_data['logged_in']) ? $user_data['logged_in'] : null;
if($user_data['logged_in'] != 1){
redirect();
}
}
public function index(){
redirect("myprofile/info");
}
public function info(){
echo"here I'll ave my info";
}
}
The problem is the error I am getting. It looks like I it can't see the sessions in the construct part of the script.
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Myprofile::$session
Filename: controllers/myprofile.php
Line Number: 6
This would be the very best solution, otherwise I need to put the same code on all the functions.
Hope to hear some feedback help. Thanks
Perhaps the session library is not loaded. Add session class on the autoload array() located in application/config/autoload.php
eg.
$autoload['libraries'] = array('database', 'session', 'output');
class Myprofile extends CI_Controller {
function __construct()
{
$this->load->library('session');
$user_data = $this->session->userdata('user_data');
$user_data['logged_in'] = isset($user_data['logged_in']) ? $user_data['logged_in'] : null;
if($user_data['logged_in'] != 1){
redirect();
}
}
public function index(){
redirect("myprofile/info");
}
public function info(){
echo"here I'll ave my info";
}
}

Code Igniter session declaration

I am new to CodeIgniter framework. I am using 2.1.4 version. I designed a simple login form, with a javascript validation, and the home page of a site. Can you please help me to understand how to declare session , and how to destroy the session on clicking signout link.
controller file of login page ( to load the view page login.php ):-
class Login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
}
function index(){
$this->load->view('login');
}
function success() {
redirect ('home');
}
}
The controller file home.php for the view home.php
class Home extends CI_Controller {
// local constructor will be overriding the one in the parent controller class
// for using a constructor in any of my Controllers
function __construct() {
parent::__construct();
}
public function index()
{
$this->load->view('home');
}
}
I have designed the view page home.php, and gave the signout link:-
<div class="logout">Signout</div>
For initializing the session, i need to know, what all constructor changes/ config changes need, and the method of session destoy.
To start session library, Go to application/config/config.php and change the below line:
$autoload['libraries'] = array('session');
It would be better if you start your session in the autoload.php. To destroy session you would use :
$this->session->sess_destroy();
To set session :
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
here is an controller... first of all u need to declare a session so that you have two choice to declare one is Go to application/config/config.php change the code as
$autoload['libraries'] = array('session');
and follow this following method (controller)
class Login extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->library('session');
}
function index(){
$this->load->view('login');
}
function success() {
$user=$this->input->post('user');
$psw=$this->input->post('pswd');
$this->load->model('validation');
$result=$this->validation->useraccess($user,$psw);
if($result)
{
$this->session->set_userdata('username', $user); //setting session
redirect ('home');
}
else
{
$this->index();
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect('login','refresh');
}
}
this is model where validation done
Class Validation extends CI_Model{
function __construct(){
parent::__construct();
}
function useraccess($user,$pswd)
{
$query = $this->db->query("select * from user where username='$user' AND password='$pswd'");
foreach ($query->result_array() as $row)
{
if($row['username']==$user AND $row['password']==$pswd)
{
return true;
}
else
{
return false;
}
}
}
}
here is a view
login page
create 2 text box and 1 submit button and declare form action as
localhost/index.php/login/success
for logut
localhost/index.php/login/logout

Resources