Only default controller is working, other controllers/routes are not - codeigniter

Just recently upgraded from Code Igniter 2.2 to Code Igniter 3.
Website is plaster.tv. The homepage works however any other URL is routed to this default_controller even though other routes are specified:
/application/config/routes.php
$route['default_controller'] = "home";
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['login'] = 'login';
$route['signup'] = 'signup';
$route['main'] = 'main';
$route['sendResetEmail'] = 'sendResetEmail';
$route['resetPassword'] = 'resetPassword';
Internal pages which is handled by other controllers, e.g. plaster.tv/signup doesn't work, but plaster.tv/?c=signup works.
/application/config/config.php:
$config['base_url'] = 'http://www.plaster.tv/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI'; //worked using AUTO in CI 2.2
$config['url_suffix'] = '';
$config['subclass_prefix'] = 'MY_';
$config['composer_autoload'] = FALSE;
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = TRUE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/application/controllers/Home.php:
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('form_validation');
}
public function index()
{
//... this part works
}
}
/application/controllers/Signup.php:
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class Signup extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
//... this class is never called when the URL is http://www.plaster.tv/signup but is called when the URL is http://www.plaster.tv/?c=signup
}
}
Hope someone could help me figure this out.

Same situation here after changing CI2 to CI3. All controllers including non-existent controller routed to the default controller.
To solve this, change $config['enable_query_strings'] = TRUE; to FALSE.

When you set $config['enable_query_strings'] = FALSE you force CodeIgniter (CI) into using query strings. That is why plaster.tv/?c=signup works but plaster.tv/signup does not.
To browse to a controller it is one way or the other, you cannot use both. If you do not want to use query strings to call a controller then you need
$config['enable_query_strings'] = TRUE;
This setting does not mean that you cannot append a query string to a URL used with CI. Any such query items will be accessible in controllers by using $this->input->get('some_key'); so long as $config['allow_get_array'] = TRUE;
Not related to your issue but you might like to know: The following lines are not needed and should be deleted
$route['login'] = 'login';
$route['signup'] = 'signup';
$route['main'] = 'main';
$route['sendResetEmail'] = 'sendResetEmail';
$route['resetPassword'] = 'resetPassword';
You only need to define routes if you want to remap CodeIgniter's normal URI relationship between a URL string and its corresponding controller/method.
Any of the above will can be browsed to with http://plaster.tv/name_of_controller without the need of any settings in routes.php - assuming there is an index() method in the requested controller.

I had the same issue and tried pretty much everything I'd read online bearing in mind I've developed many sites with Codeigniter before. But the one thing that I did change this time round was my machine and XAMPP set up. I found the issue was due to the configuration in XAMPP itself. The virtual host file wasn't configured correctly and although the default controller was working, anything else wouldn't.
What I did to rectify this was to ensure the follow lines were added to the httpd-vhosts.conf file in XAMPP:-
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName localhost
<Directory "C:/xampp/htdocs">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
</Directory>
And then each of my virtual hosts is set with the following tags:-
<VirtualHost *:80>
DocumentRoot "D:/Development Websites/testsite1/httpdocs"
ServerName testsite1.com
ErrorLog "logs/testsite1-error-log.log"
<Directory "D:/Development Websites/testsite1/httpdocs">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Order allow,deny
Allow from all
Require all granted
</Directory>
After doing this, all my controllers now work fine. It was nothing to do with CI config or .htaccess in the end.

Related

Make user-friendly URL in Codeigniter with multi-language support

I have created a multi-language website.
Facing issue while creating SEO user-friendly URL.
current URL:
http://localhost/example/en/user/myaccount OR
http://localhost/example/fr/user/myaccount
want to change it with
http://localhost/example/en/myaccount OR
http://localhost/example/fr/user/myaccount
routes.php
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
// URI like '/en/about' -> use controller 'about'
$route['^(en|de|fr|nl|id|es)/(.+)$'] = "$2";
// '/en', '/de', '/fr','/es' and '/nl' URIs -> use default controller
$route['^(en|de|fr|nl|id|es)$'] = $route['default_controller'];
also tried with
$route["myaccount"] = "user/myaccount";
$route["^(en|de|fr|nl|id|es)$/myaccount"] = "user/myaccount";
Nothing will work in this case. Already used following in routes.php file other demo projects with out multi-language. There it's work perfectly.
$route["myaccount"] = "user/myaccount";
Thanks in advance
you can consult the documentation for routes here
https://www.codeigniter.com/user_guide/general/routing.html
and for your problem
$route["(:any)/myaccount"] = "user/myaccount/$1";

How to deny access to a specific view with CodeIgniter

I would like to deny access to the admin site of a webpage created with CodeIgniter.
This is the link
www.mydomain.com/admin
I created an htaccess file with following code
Order Deny,Allow
Deny from all
Allow from xx.xxx.xxx.xxx
I put the htaccess file in application/view/admin
Obviously it does not work.
What is the correct way to deny a specific folder in a CodeIgniter project?
Edit:
Why not just add the ip check in the Admin class constructor?
public function __construct()
{
parent::__construct();
if ($this->input->ip_address() != 'xx.xxx.xxx.xxx')
{
show_404();
}
}

Dynamic CMS pages and static pages CodeIgniter

I'm using Codeigniter 2, and i have some dynamic pages (CMS) which are created from the back office and have the page name as ID . And some pages are static , there is a example :
Dynamic pages :
www.domain.com/privacy
www.domain.com/about
and static page :
www.domain.com/invitation
So the question is how can route this pages : i tried to use :
$route['([a-z0-9\-]+)'] = 'home/cms/$1';
But it gives me 404 for static pages ( www.domain.com/invitation )
Any help and thank you in advance
You can either explicitly remove the static files from the redirection in your .htaccess file:
RewriteEngine on
RewriteCond $1 !^(invitation\.php|index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
or, you can use the _remap function. Inside the _remap function, you would check for existence of a physical file for your "method" - if there, load it - if not, route to the controller method:
public function _remap($method, $params = array())
{
$filepath = BASEPATH.$method.".php";
if (file_exists($filepath))
{
include($filepath);
return;
}
else if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
else
{
show_404();
}
}

Why codeIgniter duplicating and appending URL?

When I moved my working CI webapp from my localhost to a webhosting, I encounter a "duplicating and appending URL" problem.
In my localhost, this works (shows the login page): http://mylocal/someapp/ --> which will redirect to http://mylocal/someapp/index.php/login
However, after migrating to webhosting, trying to access it like this: http://webhosting.com/someapp/, somehow it automatically appends to be
http://webhosting.com/someapp/%20//webhosting.com/someapp/index.php/login
My .htaccess contains nothing (works on localhost)
In config.php,
$config['base_url']= '';
The home controller which will redirect to the login controller (then the login view) looks like this:
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
$this->load->view('home_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home', 'refresh');
}
}
Or maybe some settings in the webhosting that I need to configure?
Use http:// prefix before base url in $config['base_url'];
e.g.
$config['base_url']=http://localhost/islam;
$config['base_url']= '';
should contain the base url of your website. i think that's the problem.
should be:
$config['base_url']= 'http://yoursite.com/';
Found the answer my self. Turns out that some webhostings are not treating CI refresh properly.
header("Refresh:0;url=...");
instead, it only wants this:
header("Location: ...");
So, I changed url_helper.php (system/helpers/url_helper.php line:543), from
case 'refresh'
to
case 'xxxrefresh'
so that it always skips the header refresh and only use header location.
I don't know if this the proper solution, but it works on my website.
Test your webhosting characteristics before you migrate your CodeIgniter codes from your local machine.
Hope this helps somebody in the future.
I had the same "duplication problem" with a local insallation. Here is my solution: set your base URL in application/config/config.php, for example:
$config['base_url'] = 'http://localhost/ci/';
It is important to add the http:// or https:// prefix to fix the "duplication problem". Of course, the trailing slash is also necessary.

How do I send data into a Code Igniter Controller index method?

I tried to encode the ID of a journal in the URL of my Code Igniter application and the retrieve it in my controller. My end goal is to access the page http://mysite.com/journal/3 and get to access a page containing details about the journal with ID 3.
In my journal.php controller file, I have
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends Controller {
public function index($journalId) {
$data['journalId'] = $journalId;
$this->view->load('journalPage', $data);
}
}
?>
In my journalPage.php view file, I have
This event has ID <?= $journalId ?>.
I wrote this rule in my routes.php file.
$route['journal/(:num)'] = 'journal/$1';
Here is the .htaccess file in my html public folder.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [QSA,L]
</IfModule>
However, when I go to mysite.com/journal/3, I get a 404 error. Why?
$route['journal/(:num)'] = 'journal/index/$1';
(:num) will become invalid if you encode
Edit:
If you use CI's encryption class to encode your ID(pointless)
you will need to modify it to make sure the string is uri safe.
Based on what I see above this is just begginers mistake on CI routing.
You .htaccess is ok (you are just removing index.php from url).
On other 2 steps (you have problem in your controller and in your routes config).
First in controller, when creating new controller you should extend CI_Controller
To make story short, this is how your journal.php file should like like:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends CI_Controller {
public function __construct() {
parent::__construct(); // This is MUST!
}
public function index($journalId) {
$data['journalId'] = $journalId;
$this->view->load('journalPage', $data);
}
}
Now when you have updated this, we come to routes config.
Config line you wrote only can confuse CI, nothing more, nothing less.
Structure of CI route shoud be like this:
$route['journal/(:any)'] = 'journal/index/$1';
This would redirect all traffic from journal/[ID] to controller named journal, to method named index with param [ID].
You must define index part in routing.
Try this, and everything should be working fine.
Cheers.
First of all: You don't need to create a empty constructor (This is must [nothing!]).
If you want to load some libraries, helpers or models at the beginning of all functions for that controller, so it is needed, otherwise it don't.
Other tip: Try to do not pass parameters on a controller function. You can catch and manipulate uri values with CodeIgniter's URI Class.
Just do this:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Journal extends CI_Controller
{
public function index()
{
$data['journalId'] = $this->uri->segment(2);
$this->view->load('journalPage', $data);
}
}
You better take a look on the URI Class. It is quite simple a handy!
http://codeigniter.com/user_guide/libraries/uri.html
PS: Don't need to fix anything on routes too.
Hug

Resources