Codeigniter dynamic routes - php

In my CI application I have a few controllers to handle different user-type functions:
CA
CD
DV
CSC
CB
So currently when someone logs in, he is redirected by his role to (example) : localhost/CA or localhost/CD etc..
I need to rewrite the routes to redirect everything depending on his role:
$route['(:any)'] = 'CA/$1'; (CA should not be hardcoded)
The rule should also be removed when using the login Controller (by filtering some url's)
Can anyone show me how to hook the rules after login? and also how to use a regexp to filter some url on which to apply the rules?
$route['^((?!auth/).)*$'] = '$1';
What other way would be to achieve this? .htaccess is out of the question since I need some data logic to create the routes.

Thanks to this wonderfull tutorial about routing from the database, I managed to add new routes after the user logs in (in my Auth controller):
class Auth extends CI_Controller {
function Auth() {
parent::__construct();
}
function index()
{
if ($this->ion_auth->logged_in())
{
$this->__checkRoles();
}
function __checkRoles()
{
$role=$this->ion_auth->get_group();
$this->save_routes($role);
redirect(base_url().'index');
}
public function save_routes($controller=null)
{
$output="<?php ";
//some uri's don't need routing
$output.="\$route['auth']='auth';";
$output.="\$route['auth/(:any)']='auth/$1';";
$output.="\$route['rest']='rest';";
$output.="\$route['rest/(:any)']='rest/$1';";
//for the rest route trough the "user-type" controller
$output.="\$route['(:any)']='".$controller."/$1';";
$this->load->helper('file');
//write to the cache file
write_file(APPPATH . "cache/routes.php", $output);
}
My routes.php looks like this:
$route['404_override'] = '';
$route['default_controller'] = "auth";
include_once(APPPATH."cache/routes.php");

It sounds like what you want is to implement remapping: the standard routing system is not designed to let you alter the routes based on whether or not the user is logged in.
However, you MIGHT (I've never seen this working) be able to put conditional statements in the standard routes.php file that checks to see if the user is logged in and what their role is (look at a session cookie or something like that) and then load different route options. Never tried it, but that MIGHT work for you.

Related

Laravel routes messed up

I'm trying to navigate to a page I created for the logged in profile of a doctor. I have not put in any authentication as I want to take care of the front end first then move to that part of the project. So basically I wanted to navigate to those pages with just putting in the url in the browser but that's not working. I'm new to laravel and am working on a project that was a template first so I'm having a bit of trouble finding things and putting in the correct paths.
I've tried putting the path in the web.php and my PagesController in a few different ways but nothing has worked so far.
my web.php :-
Route::get('/login.profile', 'Frontend\PageController#loginProfile');
my PagesController :-
public function loginProfile(){
$data['page_title'] = 'Profile';
return view('frontend/login.profile');
}
the path to the file :-
\Desktop\doctor\resources\views\frontend\login\profile.blade.php
Try to define the route like this:
Route::get('/login/profile', 'Frontend\PageController#loginProfile'); // I removed the dot from the url
and the controller method like this:
public function loginProfile(){
$data['page_title'] = 'Profile';
return view('frontend.login.profile', $data);
// also view('frontend.login.profile')->withData($data)
// and view('frontend.login.profile')->with(['data' => $data]) should work
// You will have a $data array available in the template
}
the path to the controller should be app/Http/Controllers/Frontend/PageController.php and the path to the view should be resources/views/frontend/login/profile.php.
When pointing to files, many Laravel method replace dots with slashes. That's a feature that's there to allow you to navigate/access stuff in a more "object-oriented" style, i would say. Let me know if it works.

How to achieve this kind of url routing in codeigniter

i want to achieve url routing something like www.example.com/alicia
suppose alicia is not a class name or method name just something like passing data in url and with some class i want to access this and want to use it for further process.How i can use it ? Thanks in advance.
You can use Codeigniter's built-in routing, the file route.php is located in your config folder.
there you can add:
$route['alicia'] = 'welcome/index/something';
$route['alicia/:any'] = 'welcome/index/someotherthing/$1';
then in your controller, for example welcome you just create a function like:
public function index($page = null){
if($page=='something'){
// do what you need to do, for example load a view:
$this->load->view('allaboutalicia');
}
elseif ($page=='someotherthing'){
// here you can read in data from url (www.example.com/alicia/2017
$year=$this->uri->segment(2); // you need to load the helper url previously
}else{
// do some other stuff
}
}
documentation on routing and on urlhelper
edit after comment:
in case your uri segment is representing a variable, like a username, then you should use a uri scheme like www.example.com/user/alice and create your route like:
$route['user/:any'] = 'welcome/index/user';
then in your controller welcome
public function index($page=null){
if($page=='user'){
// do what you need to do with that user
$user=$this->uri->segment(2); // you need to load the helper url
}
else{
// exception
}
}
This could be tricky because you don't want to break any existing urls that already work.
If you are using Apache, you can set up a mod_rewrite rule that takes care to exclude each of your controllers that is NOT some name.
Alternatively, you could create a remap method in your base controller.
class Welcome extends CI_Controller
{
public function _remap($method)
{
echo "request for $method being handled by " . __METHOD__;
}
}
You could write logic in that method to examine the requested $method or perhaps look at $_SERVER["REQUEST_URI"] to decide what you want to do. This can be a bit tricky to sort out but is probably a good way to get started.
Another possibility, if you can think of some way to distinguish these urls from your other urls, would be to use the routing functionality of codeigniter and define a pattern matching rule in the routes.php file that points these names to some controller which handles them.
I believe that the default_controller will be a factor in this. Any controller/method situations that actually correspond to a controller::method class should be handled by that controller::method. Any that do not match will, I believe, be assigned to your default_controller:
$route['default_controller'] = 'welcome';

Codeigniter - views in subfolders routes

For organizational purposes I need to have subfolders in my views directory. For example for managing login / registration: views/login_reg/login.php and views/login_reg/register.php.
In my URI want to see: www.mysite.com/login or www.mysite.com/register instead of www.mysite.com/login_reg/login.
I have tried the following in routes:
$route['(:any)/login'] = 'login_reg/login';
Which does not work.
EDIT:
A simple example to elaborate further:
//Controller: login_reg.php
class Login_reg{
function login(){
$this->load->view('login_reg/login');
}
function register(){
$this->load->view('login_reg/register');
}
}
//Routes:
$route['login_reg/(:any)'] = 'login_reg/$1';
So my URI looks like this: www.mysite.com/login_reg/login, or www.mysite.com/login_reg/register
So I want one controller to manage all login / registration related views. But I do not want to see the controller name in the URI. Is this possible? Or is the best approach to have a controller for login, a controller for registration, a controller for password changing etc? This seems a bit excessive. I want to have my files well organised into related directories as this is part of a very large site.
Here you don't need routing at all.
Simply add your folder name while loading view.
For example your controller name for login is like
function login()
{
//code goes here
$this->load->view('login_reg/login');
}
and similar for register.
Hope this helps you.Feel free to let me know if you further queries.
--- Update ---
To hide controller name make chanes in route.php like this;
$route['login'] = 'login_reg/login';
$route['register'] = 'login_reg/register';
and your url will go like this now :
http://yourwebsite.com/login

CodeIgniter - Stuck with routes

I am trying out CodeIgniter 2.1.4. I already have a controller for showing static pages which I built using the tutorial in CodeIgnitor documentation. I later set-up my routes like this:
// <http://localhost/> refers to <http://localhost/pages/view/>
$route['default_controller'] = "pages/view";
// <http://localhost/somepage/> refers to <http://localhost/pages/view/somepage/>
$route['(:any)'] = "pages/view/$1";
// .htaccess is already setup to rewrite the url without index.php
Now, I don't have much experience with PHP, and the concepts of URL Rewriting and MVC Architecture are fairly new to me.
Let's say there's are pages called •Home, •About, •Admin and •Contact.
For the pages •Home, •About and •Contact, the Pages controller works right as it should.
But for •Admin page, I want to have a separate controller which determines whether the user has logged in or not, and whether he has admin rights etc. And if he hasn't logged in yet, I should load the Login view instead of the Admin view.
The Pages controller has a fairly simple logic. It checks whether the string in argument, appended with .php and prepended with the views directory, exists as a file or not. If it doesn't show_404(), if it does, load view header-template, then load the page, then load view footer-templat. I'm pretty sure most of you who have worked with CodeIgniter must've seen a similar logic for static pages.
I could do redirect('login') inside my Admin view, but that doesn't seem to work. If I create a separate controller for Admin, how would I access it, while according to routes, every URL gets directed to pages/view controller (line#4 in the above code).
As I've already said, I'm fairly new to this. It might be some retarded mistake that I'm making. Or my whole MVC structure might be inappropriately built. How do I get past this and start worrying about the authentication stuff? Can anyone advise?
$route['default_controller'] = "pages/view";
$route['admin/(:any)'] = "admin/$1"; //(admin controller) with "any" method
$route['(:any)'] = "pages/view/$1";
localhost/poject/admin/edit as example
The problem you are experiencing is simple, you overwrite all controllers by that (:any) it isn't wrong but you need to manualy assign each controller that you want route as normal controller as I posted above.
please note that routes are order dependant and if one (first) is used second one is ignored. "Routes will run in the order they are defined. Higher routes will always take precedence over lower ones."
For authentification please see this post.
I would rather use _remap() and extend CI_Controller to take over my routes instead of having this route $route['(:any)'] = "pages/view/$1"; in routes.php.
remapping

CodeIgniter "default_controller" functions without controller name in URL

Forgive me if this is a "duh" question or if you need more information to answer, I am new to CodeIgniter and still haven't figured out a few things with best practices and such...
In routes.php I have $route['default_controller'] = "home"; so my default_controller is obviously "home".
Inside my home.php controller I have:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct() {
// blah
}
function index(){
// blah
}
function login(){
// blah
}
}
Which works fine and everything, there is no problems with that. The only thing I can't figure out is if I want to access the login function, I currently have to go to www.blah.com/home/login. How can I change it so it just goes to www.blah.com/login, without creating a new controller (I would like to keep some of these one time base urls all in my default controller)? Is that even possible or do I just have to create a new controller?
If I just have to create a new one, is there a best practices for how many controllers you have, etc.
Documentation says: This route will tell the Router what URI segments to use if those provided in the URL cannot be matched to a valid route.
So use $route['login'] = 'home/login';
The way I have it set up is to have the index function act as the gatekeeper: if not logged in, show a login form view, if logged in, redirect to your (protected) home page. The login function is only accessed via post, when the user submits his login/pwd, and performs the login logic.
You need add a line to your application/config/routes.php file
$route['login'] = "home/login";

Categories