CodeIgniter turn off automatic routing? - php

Is it possible to turn off the automatic routing in CodeIgniter and have it only process requests if a route for that request exists? Thanks.

Keep in mind that Dale's solution:
$route['(:any)'] = "some/default/controller/$1";
only works for one-segment URLs, like:
example.com/foo
but not for:
example.com/foo/bar
You can get around this by using a regular expression instead of the CI wildcard. And by routing to a non-existing class drops a show_404() indeed:
$route['(.*)'] = "none";

AFAIK you can't turn off CI's automatic routing, but there is a work around:
// you specific routes
$route['admin/(:any)'] = "admin/$1";
$route['search/(:any)'] = "search/$1";
// the catch all route
$route['(:any)'] = "some/default/controller/$1";
Which doesn't actually turn off CI's routing but routes all unmatched uri's to the default controller.
Alternatively you could route to a non-existent controller which I believe will throw the in built 404 error

Well, another solution could be extends the Router.
Create a class name MY_Route at /application/core/MY_Router declared as class MY_Router extends CI_Router.
You could override the method _set_routing():
This function determines what should be served based on the URI request, as well as any "routes" that have been set in the routing config file.
It should be more complex, but at least can guide you to another solution.

Codeigniter 4 solution:
app/config/Routes.php at line 24 set value true to false
$routes->setAutoRoute(false);

No, it's not possible turn off the automatic routing convention in CodeIgniter as far as I know, but you can put entries in your .htaccess file to redirect de default routes to the routes you've created.

Related

Setting Routing rules for different classes in codeigniter

My application URL "localhost/crdlabs/PHP" goes to "localhost/crdlabs/home/display/PHP" which is done using route.php. The rule is as follows.
$route['(:any)'] = "home/display/$1";
Now that I have another controller class called displayarticles(). The current URL for this class is "localhost/crdlabs/displayarticles/article/learning-coding". I understand that I cannot use the routing above for the new controller. How to set a routing rule for the current one to make the URL look like "localhost/crdlabs/learning-coding".
Note : learning-coding part is dynamically set which means there are several different articles that should go to the same controller.
Any help/advise please.
The current routing rule.
$route['(:any)'] = "home/display/$1";
Will routes anything appearing after localhost/crdlabs/argument to localhost/crdlabs/home/display/argument.So the route localhost/crdlabs/learning-coding will be redirected to localhost/crdlabs/home/display/learning-coding.So you can not use like this.
But I suggest you to show your articles
localhost/crdlabs/displayarticles/article/learning-coding
To
localhost/crdlabs/articles/learning-coding
using the following routing rule.
$route['articles/(:any)'] = "displayarticles/article/$1";
Will be best.

Remapping Codeigniter Controller

I've been playing with Codeigniter lately, and I came to know that you can remap a function inside a Controller so that you can have dynamic pretty URL.
I just want to know can the same be done with controllers? I mean If I call http://example.com/stack, it'll look for a controller named stack and if not found, it'll call a fixed/remapped controller where I can take care of it.
Can this be done?
Maybe this can help you:
function _remap( $method )
{
/// $method contains the second segment of your URI
switch( $method )
{
case 'about-me':
$this->about_me();
break;
case 'successful':
$this->display_successful_message();
break;
default:
$this->page_not_found();
break;
}
}
Yes, it can be done, you achieve it by using uri routing.
In your application/config/routes.php you can set your custom routes to remapping URIs.
There are already 2 provided, the default one (in case no controller is called) and the 404 error routing.
Now, if you want to add custom routes, you just add them UNDER those 2 defaults, keeping in mind that they're executed in the order they're presented.
Say, for example, you want to remap 'stack' to another controller, just use:
$routes['stack'] = 'othercontroller';
In this way, whenever you access 'stack' it will be automatically mapped to 'othercontroller', and if that doesn't exists..well, you get the same 404 error.
If you're hiding index.php from the URL with .htaccess remember to insert it into the $config['index_page'] = 'index.php';.
If what you're trying to achieve, instead, is a custom error message when a controller is not found, just override the 404 route as already suggested by #Juris Malinens, using your custom default controller to handle that situation
$route['404_override'] = 'customcontroller';
You can use .htaccess to do this or config/routes.php- Codeigniter is very flexible ;-)
If controller is not found use $route['404_override']; in config/routes.php
The application/config/routes.php file would be the appropriate place to do this. The 404_override mentioned by Juris is only available in CI 2.x just in case you have an older version (I don't know, you may be working on a legacy system, or may have to in the future).
Note, you can do more than just "remap" controllers with this. The routes accept regex patterns like htaccess rewrite rules; there are also some CI patterns which are basically just more human readable alias for regexes. Say you had an Articles controller with category, search and article functions, you might have routes that looked like:
$route["category/(:any)"] = "articles/category/$1";
$route["search/(:any)"] = "articles/search/$1";
$route["(:any)"] = "articles/article/$1';
You see how you can use routes to completely remove the controller name from you URLs? These rules would fall back to assuming the page is an article if the URL doesn't specifically say it's a category page or a search query. You could then check if you had an article for the URL and display a 404 as appropriate.

CodeIgniter __remap() routing more than one controller

I am trying to create a URL shortener using CodeIgniter 2.
I have 2 controllers: main and api.
For redirecting a short link through the router, I am using this setting in config/routes:
$route['(.*)'] = "main/$1";
along with a method in the main controller which should work. However, the controllers won't start. Please help me to solve this problem.
You controller "any" isnt called because it falls into that regex, so it's routed to main.
In order to exclude "any" from this rule you need to create a special rule for that, keeping in mind that for CI rules are cascading , so they're executed in the order they're presented
Note: Routes will run in the order
they are defined. Higher routes will
always take precedence over lower
ones.
So, you would have:
// reserved routes must come before custom routes
$route['default_controller'] = "home";
$route['404_override'] = '';
$route['any'] = //your rule here. maybe "any". ?
$route['(.*)'] = "main/$1"; // CI also provides you with `(:any)` rule, that mateches any character.
More on this here: Uri routing

How to set controller/action to Page Not Found

I have a controller and action which I'm accessing through a custom URL. The original route is still accessible though at the default location
zend.com/controller/action
How can I change this to simulate a "Page not found" when the user tries to access this URL? Is it possible?
If the action handler is used to respond to both URLs, you would first have to detect which URL is being requested (using $this->_request->getRequestUri()). If the default URL is detected I think the easiest way to create a "page not found" would be to use
$this->_redirect("/path/to/simulated/404/page")
and set up a controller and action to respond.
This won't actually send an HTTP 404, though. To do that, I think you would have to raise an exception within your action handler. I don't know what the official "zendy" way of doing this is, but this seems to work:
throw new Zend_Controller_Action_Exception('Not Found', 404);
You could change the main controller script to redirect a certain controller name and action name to a new page. But it's probably easier to add a new rule to the .htaccess file, indicating that this specific URL should be redirected to an error page. Example:
RewriteRule ^controller/action/?$ / [R=404,L]
Or redirect the page to an error page within your site:
RewriteRule ^controller/action/?$ /error/page-not-found/ [L]
You need to use:
$this->getResponse()->setHttpResponseCode(404);
And build your own 404 view
$this->view->message = 'Page not found';
Or you could forward to an error controller for example
$this->_forward('page-not-found', 'error');
Finally, if you have in your error controller
//...
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->view->message = 'Page not found';
break;
//...
You can just do as #bogeymin said:
throw new Zend_Controller_Action_Exception('Not Found', 404);
If you are looking other solutions than mod_rewrite based, you may create a Regex Route to match the actions you need to hide.
The other solution is to restrict access to Actions using Zend_Acl, treating each action as an ACL resource.
But the simplest and most lightweight solution is still mod_rewrite in .htaccess.
Edit:
As you can see, this may be done in numerous ways. But probably, you will need some kind of the switch, to still allow somehow to access the "hidden" action. In this case, use:
mod_rewrite for quick implementation (switching requires the person to know the .htaccess rules)
Zend_Router - the person who knows the right route can still access the feature
Zend_Acl + Zend_Auth for scalable and secure solution.
If you don't need to have authenticated users, Zend_Acl combined with Zend_Router might be the solution.
For smart handling the exceptions and building ACL's, see this (and other posts on this blog):
Handling errors in Zend Framework | CodeUtopia - The blog of Jani Hartikainen
By default the router includes default routes for :module/:controller/:action/ and :controller/:action/. You can disable these with:
$router->removeDefaultRoutes();
then only routes you setup will work. If you still want to use the default routes for some other things, you'll either have to go with one of the other answers posted or add your own 'default' routes which will match all but the modules/controllers you have custom routes for.
If you don't want to remove the default route as #Tim Fountain suggests, you should do something like this in your controller (either preDispatch or whateverAction methods)
$router = $this->getFrontController()->getRouter();
$route = $router->getCurrentRouteName();
// if we reached this controller/action from the default route, 404
if ($route == 'default')
{
throw new Zend_Controller_Action_Exception('Not Found', 404);
}
I think, all answers above are incorrect. Those show ways to achieve the same thing, but present logic at the wrong place in your application, which eventually can cause trouble later on.
The correct part of your route logic is, how extremely simple, in the routes. What is missing is that the default route Zend_Controller_Router_Route_Module does not allow you to add exceptions to specific routes. So what you need to do, is remove the default route from your routes, and add a new custom route (which should function exactly as the default route, but allows excludes) at it's place.
You can write the new route by extending the class of the default route.
class My_Custom_Route extends Zend_Controller_Router_Route_Module
{
protected $_excludes = array();
public function exclude($abc)
{
//add to $_excludes here the controller/action you want to exclude
}
public function match($abc)
{
//add functionality here that denies if the mod/contr/action is in $_excludes
//you can also add this in a separate method
//re-use parent code
}
}
You can now add add the excludes for example in a config file, and load + add the excludes at the place you initiate the new Route (and add it to the router). Off you go.

Default Controller in CodeIgniter

I am wondering if there is any other configuration options for a default controller.
For example - if I have a controller called "site" and I set the default controller in the following file: application/config/routes.php to:
$route['default_controller'] = "site";
I should be able to go to http://localhost and that brings up the
index(); function in the site controller.
However, if I try to do go to http://localhost/index.php/index2 to load the index2(); function I get a 404 error. If I change the URL to http://localhost/index.php/site/index2 it works fine - but I thought already set the default controller. Is there any way around this?
The only way to do it is manually writing the routing rule:
$route['index2'] = "site/index2";
You cannot do that.
The default_controller is only for URLs without any URI parameter. How could CodeIgniter distinguish between a method name and a controller name?
What you can do:
define a redirect inside your 404 document or directly map your 404 document to index.php
No CI doesn't work like that the first parameter has to be the name of a controller, so in this case you would have to create a controlled called "index2".

Categories