Custom routing and controller function - php

I have my routes.php as
$route['home'] = 'pages/home';
$route['login'] = 'pages/login';
$route['default_controller'] = 'pages/home';
and the controller pages.php as
class Pages extends CI_Controller {
public function home() {
$this->load->view('templates/header');
$this->load->view('pages/home');
$this->load->view('templates/one');
$this->load->view('templates/two');
$this->load->view('templates/footer');
}
public function login() {
//if ( ! file_exists('application/views/templates/'.$page.'.php')) {
// echo "no file";
// }
// $data['title'] = ucfirst($page);
$this->load->view('templates/header');
$this->load->view('templates/login');
$this->load->view('templates/footer');
}
}
Pre: I have just started with CodeIgniter and what I got from basic tutorial and after reading many stackoverflow answers is that a call for domain/login will be routed to function login in Pages class(controler) as per the the routing rule $route['login'] = 'pages/login';
The Problem: This simple code is showing 404 error. I am not getting it why it is so, as all the files are too present in templates folder. Also the normal call to domain works fine but if I call domain/home, again I get 404 error. Kindly help me what I am doing wrong.

So I am a bit new to CodeIgniter as well so I apologize at being so slow on this. The problem you are facing is that you haven't put in index.php. Your URL has to be domain/index.php/login. If you don't want to add index.php to every call then you must do the following:
add a .htaccess file in your application folder and have it look something like this:
<IfModule mod_rewrite.c>
# activate URL rewriting
RewriteEngine on
# the folders mentioned here will be accessible and not rewritten
RewriteCond $1 !^(resources|system|application|ext)
# do not rewrite for php files in the document root, robots.txt or the maintenance page
RewriteCond $1 !^([^\..]+\.php|robots\.txt)
# but rewrite everything else
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>
Turn on mode_rewrite (How to enable mod_rewrite for Apache 2.2 or https://askubuntu.com/questions/48362/how-to-enable-mod-rewrite-in-apache)
Restart your server
This will forward all domain/login requests to your front controller (index.php). The line RewriteCond $1 !^(resources|system|application|ext) will allow you to make certain folders NOT get rewritten. So if you have a folder under application named "resources" instead of it getting forwarded to domain/index.php/resources it will simply go to domain/resources.
In actuality without an .htaccess file the process is like this:
Check for domain/front_controller/route pattern in the URI and see if route exists and forward appropriately
By doing domain/login you were not following the pattern and so a 404 was delivered. Adding the front_controller (index.php) to the URI makes it follow the route pattern and gets forwarded to your route config.
Some people think the front controller in their URI is "ugly" so they add in a mod_rewrite which basically adds in the front_controller to the URI every time that directory is accessed. This way they can stick to domain/controller/action. This is also considered more secure as the only directories that can be directly accessed are the ones that are specifically stated in the rewrite.

Got it now !
Actually defining the
base_url = 'mysite.com'
in config.php just works for calling the default_controller in routing rule, and so your while mysite.com call will work normal and show you the home page, *interpreting default_controller* routing rule, but any calls for mysite.com/xyz will fail, even you have a function xyz in the main controller with routing rule as $route['xyz'] = 'pages/home',
as rest all URL calls have to be made as
domain/index.php/controller/function/arg,
and as suggested by #Bill Garrison, and also from the developer user guide of codeigniter, one should write rules in the .htaccess to remove index.php from domain name, and the url to router will then work as normal !!
For people reading out, one big advice well read the documentation thoroughly before firing the doubts. :)

Related

Redirect to Controller results 404 Page Not Found

I am creating a web application in Codeignitor using Laragon as my local server. When I try to "redirect" to a Controller - I get "404 Page Not Found". If I redirect to View - it works. I can access Controllers with other methods such as "Form Open".
Here is my .htaccess file:
RewriteEngine on
RewriteCond $1 !^(index\.php|assets|images|js|css|uploads|favicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ index.php/$1 [L]
This is my Controller - for a test I used Redirect to a View "page-login" and a Controller "Private-area". I can access the View, but the Controller sends to 404 Page Not Found.
if($this->form_validation->run()){
$result = $this->login_model->can_login($this->input->post('user_email'), $this->input->post('user_password'));
if($result == ''){
redirect('private_area');
}
else {
$this->session->set_flashdata('message', $result);
redirect('page-login');
FYI I can access Controllers (in this example "Register") using other methods such as Form Open like this:
<?php echo form_open('register/validation'); ?>
Why do I get the 404 error?
Your redirect syntax is incorrect:
the CI function redirect() is structured like this:
redirect($uri = '', $method = 'auto', $code = NULL)
keep in mind to use a relative path like '/my_controller/my_function'
as in this example:
redirect('/login/form/');
you need to autoload/load the URL helper with: $this->load->helper('url');
the form_open() syntax is correct, you need to autoload/load the Form Helper with: $this->load->helper('form');
redirect() function
Does a “header redirect” to the URI specified. If you specify the full site URL that link will be built, but for local links simply providing the URI segments to the controller you want to direct to will create the link. The function will build the URL based on your config file values. (- source)
So, the url must be
redirect("/controller/method/parameters");
Or full url
In your code, Codeigniter will look for the index() method of private_area controller.
Thanks All!
So I think #Don'tPanic nailed it. I thought "Redirect" would point to a Controller - but it points to a Route. So I created a Route in my Routes.php file where
$route['private_area'] = 'private_area';
And everything works. Is this the correct way to do this?
Ie to define Routes in the Routes.php file...then call upon them as required using "Redirect"?

Codeigniter subdomain 404 Not Found

I'm new to codeigniter and I'm working on a project that is done on this framework. When I try to access a url such as "mysite.com/about", it gives me and an error
404 Not found,
I tried many .htaccess file on wamp and a live host but the result is the same.
I can Access these file by using "mysite.com/index.php/about" but I want to access as this "mysite.com/about" this not only for about page but all so very page that I try to access by using like this "mysite.com/contact-us"
.How do I fix this?
Write this code in your .htaccess file and in wamp server click on rewrite_module
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
IndexIgnore *
</IfModule>
By default, Codeigniter will call the about controller, unless a method is provided in the second uri segment, the index() method will be loaded.
If the index() method doesn't exist, it will 404.
The other way of doing it is to add a line in your application/config/routes.php file. Such as:
$route['about'] = 'main/about';
This means, a request where the url matches /about will map to main/about
Main being the controller and about being the method within that for example.
See this part of the documentation for a more detailed explaination
https://www.codeigniter.com/userguide3/general/routing.html
Hope this helps
Make sure that you have named the Class for your controller as the controllers file name. Then try to access the page as shown in the code below.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pages extends CI_Controller {
function about()
{
$data['title'] = 'About us Page';
$this->load->view('about', $data); //about is in views
}
}
?>
The file name should be pages.php in this case.
To access the about page type in this link mysite.com/index.php?/controllerfolder/pages/about.
If you want clean url and remove index.php? edit your htaccess. Use this link to know how to edit your htaccess
https://www.formget.com/codeigniter-htaccess-remove-index-php/.
Hope this is helpful. Thanks

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.

Can't make admin landing page work

I'm not really new with Codeigniter but have been working on started projects so far. Now I'm starting a new small project on my own and I'm kinda lost.
I downloaded codeigniter, configured all the parameters in wamp so I have this base URL: http://local.project
Now I'm trying to build a small admin. I should be able to enter to this admin through http://local.project/admin which should show a login page. I already have a template for this.
The thing is that same 404 error appears. The configuration I have is this:
Inside config folder, routes.php:
$route['default_controller'] = "admin";
$route['404_override'] = '';
$route['admin'] = 'admin';
then on controllers folder, created another folder admin with a file also called admin.php which contains:
<?php
class Admin extends CI_Controller {
public function index()
{
echo 'Hello World!';
}
}
?>
now, trying to access from the browser I've tried many possible url but I'm still not sure of how it should be>
http://local.project/admin
and other combinations like
http://local.project/admin/index.php
http://local.project/index
http://local.project/index/admin
but always appears error 404 page not found.
So I'm really wondering, what am I doing wrong?
EDIT
this is what .htaccess contains>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
You're perfectly reasonable to assume that by defining a default controller it should work in subfolders, but ellislabs doesn't agree. As per the user guide:
$route['default_controller'] = 'welcome';
This route indicates which controller class should be loaded if the
URI contains no data, which will be the case when people load your
root URL. In the above example, the "welcome" class would be loaded.
You are encouraged to always have a default route otherwise a 404 page
will appear by default.
The key words there are "if the URI contains no data." "/admin" contains data. If you put your Admin controller in the root controllers folder and put in "local.project/" you'd get the index function of the Admin controller, but in a subfolder, you have to specify the full path, which in this case would be "/admin/admin/index." Putting that into your "admin" route will fix the issue, and then adding another route to take care of any other functions ($route["admin/(:any)'] = 'admin/admin/$1' should do the trick) will fix the rest.
And just so you know, if you ever upload this code to a server running Linux, it'll break because "Admin" and "admin" are two different controllers as far as Linux/Unix are concerned. As a long-time Windows dev, I feel your pain on that one.

Categories