default routing in codeigniter - php

I'm exploring codeigniter. On app startup default controller is changed to load my controller.
Controller properly loads the view and that's fine, so I'm guessing routing works as expected, but when I use (manually type on address bar other method on same controller) same url pattern /controller/method I'm getting 404 error, either view exist.
Do have to change some default routing behavior or something else is problem?
Thanks

I dont know if you already removed index.php from your url pattern, assuming that's the case you should type inside browser address field index.php/controller/method. (if you manually type url as you describe)
If you on the other hand do not want to use index.php on every link you can consider to remove that, more info here.

Well this may be the because of index.php file as mentioned above or else if you would like get rid of index.php Kindly include .htaccess file in your application.
config/config.php - modifiy
$config['base_url'] = 'index.php'
$config['base_url'] = '' // set it to blank
For .htaccess file refer the below code
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

follow this
root_folder/.htaccess
to remove index.php in url
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
set base URL
root_folder/application/config/config.php
| to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise.
| The auto-detection mechanism exists only for convenience during
| development and MUST NOT be used in production!
|
| If you need to allow multiple domains, remember that this file is still
| a PHP script and you can easily do that on your own.
|
*/
$config['base_url'] = 'http://[::1]/my-project/';
removing index.php in url, even on request post in form
root_folder/application/config/config.php
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
set default controller, mine is 'home'
root_folder/application/config/routes.php
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'home';
after that, make sure that the all controller file name is capitalize.
also a class name.
this is also important mostly when you need to upload in a live
server.
root_folder/application/controllers/Home.php
<?php
/**
*
*
* #author Lloric Garcia <emorickfighter#gmail.com>
*/
defined('BASEPATH') OR exit('No direct script access allowed');
class Home extends MY_Controller {
public function index() {
}
}
then this will be you url
http://[::1]/my-project/home
that is my set up even in live server
all of this came from
https://www.codeigniter.com/userguide3/index.html

Related

Code-igniter controllers file name can not start with capital letter

I was using small letter for controller file name before,
however, recently move the file to other server that need to controller name to be start with capital
=========================================
Here is the rename example :
file name: Home.php
$route['default_controller']: "home";
link: http://example.com/index_folder/
==========================================
it show error of
Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.
And when I change the route to
$route['default_controller']: "Home";
it still show the same error,
Only success if I go to
http://example.com/index_folder/Home/
How to fix that? Thanks for helping
Update
Here is the htaccess file, at the root of the project folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
The reason of rename is it seems the new server has problem if my Controller is in lower case
Linux is case sensitive, keep the file name and class name same and try again. It will work.
The same code will work fine on windows but give exception on Linux.
As per Documentation,
class Home extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
}
Then save the file to your application/controllers/ directory.
Important:-
The file must be called ‘Home.php’, with a capital ‘H’.
Now visit the your site using a URL similar to this:
example.com/index.php/home/
CodeIgniter can be told to load a default controller when a URI is not present, as will be the case when only your site root URL is requested.
To specify a default controller, open your application/config/routes.php file and set this variable:
$route['default_controller'] = 'home';
Where ‘home’ is the name of the controller class you want used.
If you now load your main index.php file without specifying any URI segments you’ll see your “Hello World” message by default.

CodeIgniter - redirect subdomains set to folder in "controllers"

I'm trying to make any or a set of subdomains redirect to a folder inside "controllers" folder of a CI installation. I've tried a bunch of stuff found here on SO but none work for my project or have the same specs I need. Since I am a bit of a noob when it comes to .htaccess so I've figured I might just ask someone more qualified in here. Here are the specs:
using this awesome .htaccess file as a base
need to redirect at least this three subdomains (www|admin|api) to /application/controllers/(www|admin|api) equivalent folders
without loosing the REQUEST_URI (just saying)
and without actually changing the URL in the address bar
Example: http://api.domain.com/some/uri/segments should internally redirect to CI_installation_folder/application/controllers/api/some/uri/segments
I've tried something like this (and variations):
RewriteCond %{HTTP_HOST} ^(www|admin|api) [NC]
RewriteRule ^(.*)$ /%1/$1 [L,R=301]
or replaced the RewriteRule with 2 other lines like so:
RewriteCond %{ENV:REDIRECTED} !true
RewriteRule ^(.*)$ [L,R=301,E=REDIRECTED:true]
to prevent the loop, but all I can get is either a looping redirect (1st case) or even a 500 server error on some variations :(
Adding this
RewriteCond %{REQUEST_URI} !^/(www|admin|api) [NC]
will also not work since I'm not changing the URL in the address bar. I also haven't got any success with the [P] flag also.
Can anyone help? Thanks!
Did you try using the route configuration of Codeigniter?
you don't have to use htaccess rewrite - although its a valid approach, you can just check for the subdomain in the config/route.php file and set the routing for your subdomains.
switch ($_SERVER['HTTP_HOST']) {
case 'admin.domain.com':
$route['(:any)'] = "admin/$1"; // this will set any uri and add the controler fodler to it
$route['default_controller'] = "admin/home"; // set the default controller for this subdomain
break;
case 'api.domain.com':
$route['(:any)'] = "api/$1"; // this will set any uri and add the controler fodler to it
$route['default_controller'] = "api/home"; // set the default controller for this subdomain
break;
}
If you would like it to be a more generic/ dynamic routing, you can have it like this (in the same config/route.php file):
$controllerFolderName = array_shift((explode(".",$_SERVER['HTTP_HOST'])));
$route['(:any)'] = $controllerFolderName."/$1";
$route['default_controller'] = $controllerFolderName."/home";
this routing will work for all subdomains and will set the default routing to a folder inside the controller folder with the same name as the subdomain, so for a domain like api.domain.com you will have the route set to api etc.
it is important that you keep the same logic for all folder name that they will always match your subdomain and i would also suggest to add an error handling system for visitors with no subdomain (http://domain.com) and for cases where you have the subdomain but a folder with that name does not exists (you can do that with file_exits)
After a few more hours of digging I think I solved the problem. Here's how (for the ones that care):
# Subdomains to Folders + Enforce www
RewriteCond %{HTTP_HOST} ^(www|admin|api) [NC]
RewriteRule ^(.*)$ http://www.localhost/%1/$1 [L,P,S=1]
RewriteRule ^(.*)$ http://www.localhost/$1 [L,R=301]
I combined the internal redirect with the www enforcer rule. All there is to do after this is configure the Apache Server to accept and properly redirect the PROXY request :)
Have phun!
Tried the suggestions above but ran into a lot of issues. Found a solution that allows you to route all URIs to a directory based on the subdomain, while allowing you to use the codeigniter routing functionality as it was intended.
First, place the follwing code in your application/core folder:
class MY_Router extends CI_Router {
public function __construct($routing=NULL) {
$routing['directory'] = explode('.',$_SERVER['HTTP_HOST'])[0];
parent::__construct($routing);
}
}
Codeigniter will now place you subdomain directory before all controllers when routing. (i.e. ...application/subdomain_dir/class/method)
Next, set your base_url in the config.php file.
$subdomain = explode('.',$_SERVER['HTTP_HOST'])[0];
$config['base_url'] = 'http://'.$subdomain.'.domain.com';
Finally, use the routes.php as it was intended.
$route['default_controller'] = "home";
The default controller above will now be routed to subdomain_dir/home. Similarly, if you navigate to subdomain.domain.com/class/method, you will be routed to subdomain_dir/class/method.
Hope this helps someone in the future.

unable to load your default controller on Codeigniter

This is the error that i am getting.
Please make sure the controller specified in your Routes.php file is valid.
Let me explain this.
In my application i have used HMVC. In my application folder there are two folders back-modules and front-modules.in my front-modules folder there is a folder called "home" and it has controllers,modules and views.
controllers->home.php
this is my home.php
class Home extends MX_Controller{
public function __construct(){
parent::__construct();
$this->load->helper(array('form'));
}
public function index(){
$this->template->build('home');
}
}
and this is my routes.php
$route['default_controller'] = "home";
$route['404_override'] = '';
when i try to go to the site, it gives this error
unable to load your default controller on Codeigniter.Please make sure the controller specified in your Routes.php file is valid.
this system works fine on localhost.
Someone please help me in this matter.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:
example.com/class/function/id/
your 'default_controller' should be:
$route['default_controller'] = "home/index";
read official CodeIgniter URI Routing Documentation
Kindly Check .htaccess file exist or not in root place of your website.
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1
Some times codeigniter won't find the controller.
Go to config > routers.php
and see the value of default_controller
make a controller in controllers folder with the same value.
According to codegniter manual managing multi application
in your index.php file change
$application_folder = 'application';
to
$application_folder = 'application/home';
and make sure the controller file name starts with capital letter
controllers->Home.php
and keep Routes.php configurations
$route['default_controller'] = "home";

Trouble with CodeIgniter routes, getting 404 errors

I am trying to create custom routes for my CodeIgniter site. Even the most basic routes do not work. For example I have the welcome controller mapped to "test" and it just 404's on me. I am running on MAMP with mod_rewrite enabled.
I have the index.php line in config.php empty..
$config['index_page'] = '';
Here is my .htacess file..
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php/$1 [L,QSA]
And here is my route..
$route['welcome'] = 'test';
In a route, the array key contains the URI to be matched, while the
array value contains the destination it should be re-routed to.
-- CI Documentation
Your physical controller name is welcome. So if you want a URL containing the word test in the first segment be remapped to the welcome class, you should do this:
$route['test'] = "welcome/METHOD";
Where METHOD is method of welcome class.
Note: If class/method was welcome/index, you do NOT need to append /index.
If I read this correctly, that route will try to redirect the controller 'welcome' to the controller 'test'. If you have a controller named 'test' and a function named 'index', you can route the following:
route['welcome/index'] = 'test/index';
Is that what you are trying to do?
A couple things:
Routes in CI are cascaded, they're evaluated top to bottom, and the router stops at the first match. Make sure, then, to have any custom route placed below the 2 default routes in a vanilla distribution:
$route['default_controller'] = "welcome";
$route['404_override'] = '';
// custom routes here
$route['welcome'] = "welcome/test";
If you have a controller named "welcome" (the default one), and you want to call a method named "test", you need a route like
$route['welcome'] = "welcome/test"
which will be accessible at the url http://wwww.yourdomain.com/welcome
(if no route were specified, you would have accessed it like http://www.yourdomain.com/welcome/test)
Usually, controller have an index method which is called automatically when no other method is provided. The route you've created so far isn't working because it's calling the index() method of a "test" controller, which is likely not present.
A suggestion: if you mainatain the "welcome" controller as the default one, and you want to call an url like http://www.yourdomain.com/test
You need a test() method and your route must be
$route['test'] = "welcome/test";

CodeIgniter subfolders and URI routing

I’ve read the manual on URI routing and views and something is not clicking with me.
In my views folder, I have a subfolder called products. In there is a file called product_view. In my controller, I have:
function index() {
$data['title'] = 'Product Overview';
$data['main_content'] = 'products/product_view';
$this->load->view('templates/main.php', $data);
}
The template loads a header view, a footer view and a navigation view, plus the view as a main content variable.
In my URI routing, I have:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['scaffolding_trigger'] = 'scaffolding';
|
| This route lets you set a "secret" word that will trigger the
| scaffolding feature for added security. Note: Scaffolding must be
| enabled in the controller in which you intend to use it. The reserved
| routes must come before any wildcard or regular expression routes.
|
*/
$route['default_controller'] = "index_controller";
$route['laser-configurator'] = "configurator";
$route['news-and-events'] = "news";
$route['products/product-overview'] = "products/product_view";
$route['scaffolding_trigger'] = "";
/* End of file routes.php */
/* Location: ./system/application/config/routes.php */
This causes a 404 error when I try to go to domain.com/products/product-overview. Do I need to do something with my .htaccess? If so, what? Here is my .htaccess:
Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
I’d appreciate some specific help, as the documentation isn’t specific on how to address this. I’ve done a little searching in the forums, and didn’t see anything, but I’m posting this while I keep looking.
In CI URIs are routed by the name of your controller and the name of the method in the controller.
If the controller is named "products.php" the function for the corresponding view is called "index", the correct URI for that page is "/products".
So your code should be
$route['products/product-overview'] = 'products/index';
To use multi-level directory structure for your controllers use router extention talked about in this post, I have used it on occasion, and can vouch for it working.

Categories