Rewrite URL if user tried to access any non existing controller.
Ex:- If user tried to access http://example.com/project/anyvalue . In my program there is no controller with name 'anyvalue'. In this situation I want to redirect to
http://example.com/project/profile/anyvalue
How is this possible using routing in codeigniter?
Use default route to redirect requests to some particular page if controller is missing
You can find routes location in
/application/admin/config/routes.php
$route['default_controller'] = "welcome";
Also use following in case of page not found
$route['404_override'] = 'default_page';
Add routes to all existing controllers under "/project/..."
Add a route that will match any paths under "/project"
Example:
/* Currently available controllers under "/project/" */
$route['project/profile'] = "project/profile";
$route['project/add'] = "project/add";
$route['project/edit'] = "project/edit";
/* Catch all others under "/project/" */
$route['project/(:any)'] = "project/profile/$1";
/* if controller class name is Profile and function name is index */
$route['project/(:any)'] = 'project/profile/index/$1';
What you want is Vanity URLs, you can find a guide for performing this in code igniter here:
http://philpalmieri.com/2010/04/personalized-user-vanity-urls-in-codeigniter/
Essentially you're adding this to your routes file:
$handle = opendir(APPPATH."/modules");
while (false !== ($file = readdir($handle))) {
if(is_dir(APPPATH."/modules/".$file)){
$route[$file] = $file;
$route[$file."/(.*)"] = $file."/$1";
}
}
/*Your custom routes here*/
/*Wrap up, anything that isnt accounted for pushes to the alias check*/
$route['([a-z\-_\/]+)'] = "aliases/check/$1";
Related
-Myproject
-application
-controllers
-subfolder1
-subfolder2
-subfolder3
-subfolder(..n)
Controller.php
And need to set routes.php
$route['default_controller'] = 'subfolder1/subfolder2/subfolder3/subfolder(..n)/controller';
According to the examples in the docs it does not appear that you can put a Controller more than one level deep inside a subdirectory.
example.com/index.php/subdirectory/controller/function
I also don't think your route looks correct. You would not have home/ at the start of the route unless "home" is a controller or subdirectory name. See examples here.
$route['default_controller'] = 'subdirectory/controller';
I have researched and found in codeigniter 3 system/core/Router.php library file's method _set_default_controller() can not support default controller in subfolder. So i have overrided/ customized this method _set_default_controller() and now it supports n level subfolders and working fine for me.
I have created application/core/MY_Router.php with the below code to override this method _set_default_controller()
<?php
/**
* Override Set default controller
*
* #author : amit
*
* #return void
*/
protected function _set_default_controller()
{
if (empty($this->default_controller))
{
show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
}
// Is the method being specified?
$x = explode('/', $this->default_controller);
$dir = APPPATH.'controllers'; // set the controllers directrory path
$dir_arr = array();
foreach($x as $key => $val){
if(!is_dir($dir.'/'.$val)){
// find out class i.e. controller
if(file_exists($dir.'/'.ucfirst($val).'.php')){
$class = $val;
if(array_key_exists(($key+1), $x)){
$method = $x[$key+1]; // find out method i.e. action
}else{
$method = 'index'; // default method i.e. action
}
}else{
// show error message if the specified controller not found
show_error('Not found specified default controller : '. $this->default_controller);
}
break;
}
$dir_arr[] = $val;
$dir = $dir.'/'.$val;
}
//set directory
$this->set_directory(implode('/', $dir_arr));
$this->set_class($class);
$this->set_method($method);
// Assign routed segments, index starting from 1
$this->uri->rsegments = array(
1 => $class,
2 => $method
);
log_message('debug', 'No URI present. Default controller set.');
}
?>
Now we can set default controller in application/config/routes.php like below
// without action method name
$route['default_controller'] = 'subfoler1/subfoler2/subfolder3/subfolder(..n)/controller';
OR
// with action method name
$route['default_controller'] = 'subfoler1/subfoler2/subfolder3/subfolder(..n)/controller/action';
If we will pass the action method name it will detect that method as action and if we will not pass action name then it will assume index as a action.
I need to make custom URL in Codeiginter to display links from
domain.com/news/id/1
to
domain.com/article-name.html
i want it dynamic to all news id not just one link
can i do it in codeiginter or not ?
Yes you can, This is called URL rewrite. I can explain here but the official documentation is far better.
here it is: http://ellislab.com/codeigniter/user-guide/general/urls.html
In your config.php file do this:
$config['url_suffix'] = '.html'; // this line might actually not be necessary, i forget
In routes.php set this:
$route['article-name.html'] = "news/id/1";
Let me know if you get any errors.
UPDATE
Step 1: Set your default controller in routes.php
$route['default_controller'] = 'get_article';
Step 2: Set your config.php to put .html on the end
$config['url_suffix'] = '.html';
Step 3: Create the Controller
// path: /codeigniter/2.1.4/yourAppName/controllers/get_article.php
<?php
class Get_article extends CI_Controller {
public function index($article = '')
{
// $article will be "article-name.html" or "article2-name.html"
if($article != '')
{
$pieces = explode('.', $article);
// $pieces[0] will be "article-name"
// $pieces[1] will be "html"
// Database call to find article name
// you do this
$this->load->view('yourArticleView', $dbDataArray);
}
else
{
// show a default article or something
}
}
}
?>
I'm working on a project built in codeigniter that makes heavy use of routes and the remap function to rewrite urls. The current implementation is confusing and messy.
Essentially this is what the designer was trying to accomplish:
www.example.com/controller/method/arg1/
TO
www.example.com/arg1/controller/method/
Can anyone suggest a clean way of accomplishing this?
This actually only needs to happen for one specific controller. It's fine if all other controllers need to simply follow the normal /controller/model/arg1... pattern
Just to give you an idea of how the current code looks here is the 'routes' file: (not really looking into any insight into this code, just want to give you an idea of how cluttered this current setup is that I'm dealing with. I want to just throw this away and replace it with something better)
// we need to specify admin controller and functions so they are not treated as a contest
$route['admin/users'] = 'admin/users';
$route['admin/users/(:any)'] = 'admin/users/$1';
$route['admin'] = 'admin/index/';
$route['admin/(:any)'] = 'admin/$1';
// same goes for sessions and any other controllers
$route['session'] = 'session/index/';
$route['session/(:any)'] = 'session/$1';
// forward http://localhost/ball/contests to controller contests method index
$route['(:any)/contests'] = 'contests/index/$1';
// forward http://localhost/ball/contests/vote (example) to controller contests method $2 (variable)
$route['(:any)/contests/(:any)'] = 'contests/index/$1/$2';
// forward http://localhost/ball/contests/users/login (example) to controller users method $2 (variable)
$route['(:any)/users/(:any)'] = 'users/index/$1/$2';
// if in doubt forward to contests to see if its a contest
// this controller will 404 any invalid requests
$route['(:any)'] = 'contests/index/$1';
$route['testing/'] = 'testing/';
And the remap function that goes with it:
public function _remap($method, $params = array()){
// example $params = array('ball', 'vote')
// params[0] = 'ball', params[1] = 'vote'
/*
* Write a detailed explanation for why this method is used and that it's attempting to accomplish.
* Currently there is no documentation detailing what you're trying to accomplish with the url here.
* Explain how this moves the contest name url segment infront of the controller url segment. Also
* explain how this works with the routing class.
* */
$count = count($params);
if($count == 0){ // no contest specified
redirect('http://messageamp.com');
return;
}
$contest_name = $params[0];
unset($params[0]); //remove the contest name from params array because we are feeding this to codeigniter
if($count < 2) // no method specified
$method = 'index';
else{
$method = $params[1];
unset($params[1]);
}
//We need to scrap this, lazy-loading is a best-practice we should be following
$this->init(); //load models
//make sure contest is valid or 404 it
if(!$this->central->_check_contest($contest_name)){
show_404();
return;
}
$this->data['controller'] = 'contests';
$this->data['method'] = $method;
$this->data['params'] = $params;
// call the function if exists
if(method_exists($this, $method)){
return call_user_func_array(array($this, $method), $params);
}
show_404(); // this will only be reached if method doesn't exist
}
To get something like this:
www.example.com/controller/method/arg1/ TO www.example.com/arg1/controller/method/
You could do this in your routes.php config:
$route['(:any)/(:any)/(:any)'] = "$2/$3/$1";
However, if you want to have all of your other classes stick to the default routing, you would need to create routes for each of them to overwrite this default route:
$route['controller_name/(:any)'] = "controller_name/$1";
Hi i wont to make something like that.
http:// example.com/ - Main Controller
http:// example.com/rules/ - Main Controller where content get from database, but if not exist
return 404 page. (It's ok, isn't problem.)
But if i have subfolder in application/controlles/rules/
I want to redirect it to Main Contorller at Rules folder.
This follow code can solve problem, but i don't know how it right realise.
At routes.php:
$route['default_controller'] = "main";
$route['404_override'] = '';
$dirtest = $route['(:any)'];
if (is_dir(APPPATH.'controllers/'.$dirtest)) {
$route['(:any)'] = $dirtest.'/$1';
} else {
$route['(:any)'] = 'main/index/$1';
}
Ok, what I have:
controllers/main.php
class Main extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('main_model');
}
public function index($method = null)
{
if (is_dir(APPPATH.'controllers/'.$method)) {
// Need re-rout to the application/controllers/$method/
} else {
if ($query = $this->main_model->get_content($method)) {
$data['content'] = $query[0]->text;
// it shows at views/main.php
} else {
show_404($method);
}
}
$data['main_content'] = 'main';
$this->load->view('includes/template', $data);
}
}
Updated Again (routes.php):
So, seem's like what i search (work example):
$route['default_controller'] = "main";
$route['404_override'] = '';
$subfolders = glob(APPPATH.'controllers/*', GLOB_ONLYDIR);
foreach ($subfolders as $folder) {
$folder = preg_replace('/application\/controllers\//', '', $folder);
$route[$folder] = $folder.'/main/index/';
$route[$folder.'/(:any)'] = $folder.'/main/$1';
}
$route['(:any)'] = 'main/index/$1';
But, in perfectly need some like this:
http:// example.com/1/2/3/4/5/6/...
Folder "controllers" has subfolder "1"?
YES: Folder "1" has subfolder "2"?
NO: Folder "1" has controller "2.php"?
NO: Controller "controllers/1/main.php" has function "2"?
YES: redirect to http:// example.com/1/2/ - where 3,4,5 - parameters..
It is realy nice, when you have structure like:
http://example.com/blog/ - recent blog's posts
http://example.com/blog/2007/ - recent from 2007 year blog's posts
http://example.com/blog/2007/06/ - same with month number
http://example.com/blog/2007/06/29/ - same with day number
http://example.com/blog/web-design/ - recent blog's post's about web design
http://example.com/blog/web-design/2007/ - blog' posts about web design from 2007 years.
http://example.com/blog/current-post-title/ - current post
Same interesting i find http://codeigniter.com/forums/viewthread/97024/#490613
I didn't thoroughly read your question, but this immediately caught my attention:
if (is_dir($path . '/' . $folder)) {
echo "$route['$folder/(:any)'] = '$folder/index/$1';"; //<---- why echo ???
}
Honestly I'm not sure why this didn't cause serious issues for you in addition to not working.
You don't want to echo the route here, that will just try to print the string to screen, it's not even interpreted as PHP this way. There are also some issues with quotes that need to be remedied so the variables can be read as variables, not strings. Try this instead:
if (is_dir($path . '/' . $folder)) {
$route[$folder.'/(:any)'] = $folder.'/index/$1';
}
Aside: I'd like to offer some additional resources that are not directly related to your problem, but should help you nonetheless with a solution:
Preferred way to remap calls to controllers: http://codeigniter.com/user_guide/general/controllers.html#remapping
Easier way to scan directories: http://php.net/manual/en/function.glob.php
It's hard to say why the registering of your routes fails. From your code I can see that you're not registering the routes (you just echo them), additionally I see that the usage of variables in strings are used inconsistently. Probably you mixed this a bit, the codeigniter documentation about routes is not precise on it either (in some minor points, their code examples are not really syntactically correct, but overall it's good).
I suggest you first move the logic to register your dynamic routes into a function of it's own. This will keep things a bit more modular and you can more easily change things and you don't pollute the global namespace with variables.
Based on this, I've refactored your code a bit. It does not mean that this works (not tested), however it might make things more clear when you read it:
function register_dynamic_routes($path, array &$route)
{
$nodes = scandir($path);
if (false === $nodes)
{
throw new InvalidArgumentException(sprintf('Path parameter invalid. scandir("$path") failed.', $path));
}
foreach ($nodes as $node)
{
if ($node === '.' or $node === '..')
continue
;
if (!is_dir("{$path}/{$node}")
continue
;
$routeDef = "{$folder}/(:any)";
$routeResolve = "{$folder}/index/\$1";
$route[$routeDef] = $routeResolve;
# FIXME debug output
echo "\$route['{$routeDef}'] = '{$routeResolve}';";
}
}
$path = APPPATH.'controllers/';
register_dynamic_routes($path, $route);
$route['(:any)'] = 'main/index/$1';
Next to this you probably might not want to shift everything onto the index action, but a dynamic action instead. Furthermore, you might want to have a base controller that is delegating everything into the sub-controllers instead of adding the routes per controller. But that's up to you. The example above is based on the directory approach you outlined in your question.
Edit: Additional information is available in the Controllers section next to the URI Routing section
All this seems kind of complicated.
Plus, if you have hundreds (or thousands or more?) of possible routes in a database you may not want to load all of them into the "$routes" array every time any page loads in your application.
Instead, why not just do this?
last line of routes.php:
$route['404_override'] = 'vanity';
Controller file: Vanity.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Vanity extends MY_Controller {
/**
* Vanity Page controller.
*
*/
public function __construct() {
parent::__construct();
}
public function index()
{
$url = $_SERVER['PHP_SELF'];
$url = str_replace("/index.php/", "", $url);
// you could check here if $url is valid. If not, then load 404 via:
//
// show_404();
//
// or, if it is valid then load the appropriate view, redirect, or
// whatever else it is you needed to do!
echo "Hello from page " . $url;
exit;
}
}
?>
I'd like to obtain a list of all controllers in a Codeiginiter project so I can easily loop through each of them and add defined routes. I can't seem to find a method that will give me what I'm after ?
Here is the code snippet from the routes.php file where I would like to access the array: -
// I'd like $controllers to be dynamically populated by a method
//
$controllers = array('pages', 'users');
// Loop through each controller and add controller/action routes
//
foreach ($controllers as $controller) {
$route[$controller] = $controller . '/index';
$route[$controller . '/(.+)'] = $controller . '/$1';
}
// Any URL that doesn't have a / in it should be tried as an action against
// the pages controller
//
$route['([^\/]+)$'] = 'pages/$1';
UPDATE #1
To explain a little more what I'm trying to achieve.. I have a Pages controller which contains pages such as about, contact-us, privacy etc. These pages should all be accessible via /about, /contact-us and /privacy. So basically, any action/method in the Pages controller should be accessible without having to specify /pages/<action>.
Not sure if I'm going about this the right way ?
Well to directly answer to coding question, you can do this:
foreach(glob(APPPATH . 'controllers/*' . EXT) as $controller)
{
$controller = basename($controller, EXT);
$route[$controller] = $controller . '/index';
$route[$controller . '/(.+)'] = $controller . '/$1';
}
Buuuuuut this may not work out to be the most flexible method further down the line.
There are a few other ways to do it. One is to create a MY_Router and insert
$this->set_class('pages');
$this->set_method($segments[0]);
before/instead of show_404();
That will send /contact to /pages/contact, but only if no controllers, methods, routes are mapped to first.
OOOOOOORRRRRR use Modular Separation and add the following to your main routes.php
$routes['404'] = 'pages';