Codeigniter 3 Routes and 404 Pages - php

I'm developing a web application and i'm slightly confused by routes and how they work.
My web application has an admin area and the URL structure is as follows;
example.com/admin/view/form/123
My Admin controller looks like this;
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller {
public function index()
{
$data = array(
'title' => 'Admin Page'
);
$this->load->view('admin/index', $data);
}
public function view() {
$form_submission_id = $this->uri->segment(4);
$records = $this->Admin_model->getDetails($form_submission_id);
$data = array(
'title' => 'Form Details',
'records' => $records
);
$this->load->view('admin/view/index', $data);
}
}
I don't have any custom routes setup.
When I visit the following URL, I can see the page and corresponding data successfully;
example.com/admin/view/form/123
But, when I change the /form/ URL segment to something random like below I can still see the correct data;
example.com/admin/view/foo/123
Why is this?
I was expecting to see a 404 page?
What do I need to change in order to achieve what I want?
Perhaps i'm misunderstanding the logic and should have my controllers / routes setup differently?

Codeigiter URL has a structure as domain/controllerName/actionName/param1/param2 and so on. In your code URL example.com/admin/view/form/123 admin is controller, view is action name and form and 123 is the parameters which you passed using get method. You can access these parameters like $this->uri->segment(3).
Thus in your code:
It will not show any error as your function is not even using 3rd URI segment.
It will not show 404 page as it found correct controller and action.
To achieve domain related functionality, you need to either change for function code accordingly or need to use routes for this.
Hope it helps you to clarify this code.

Rohit Mittal answer is good and also,
You can change the view fuction in admin controller like as:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller {
public function view($form = null,$form_submission_id = null) {
if($form == "form" && $form_submission_id){
$records = $this->Admin_model->getDetails($form_submission_id);
$data = array(
'title' => 'Form Details',
'records' => $records
);
$this->load->view('admin/view/index', $data);
}
}

Related

Codeigniter 3 Routes and Handling 404 Errors

I am trying to configure pretty URLs in codeigniter and it's not making much sense to me. I'd like my URLs to follow the following structure;
example.com/admin/view/form/123
I can successfully view data when I visit the URL above. I see the same data when I visit;
example.com/admin/view/123
Notice the 3rd segment /form/ is missing, but still returns the data. It's almost like it's ignoring this - I thought CI should throw a 404 error, or do I need to check for this manually? If so, how?
When I visit this URL;
example.com/admin/view
I see the following error;
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Admin::view(), 0 passed
My code can be seen below;
Controller
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->database();
$this->load->model('Admin_model');
}
public function index()
{
$this->load->view('template/header');
$data = array(
'title' => 'Admin Page'
);
$this->load->view('admin/index', $data);
$this->load->view('template/footer');
}
public function view($form_submission_id)
{
$this->load->view('template/header');
$data = array(
'title' => 'Form View Page',
'record' => $this->Admin_model->getSubmissionById($form_submission_id)
);
$this->load->view('admin/view/index', $data);
$this->load->view('template/footer');
}
}
Model
class Admin_model extends CI_Model {
public function getSubmissionById($form_submission_id) {
$this->db->select('*');
$this->db->from('submissions');
$this->db->where('id', $form_submission_id);
$query = $this->db->get();
return $query->row();
}
}
Routes
// redirect any urls that contain a number after /form
$route['admin/view/form/(:num)'] = "admin/view/$1";
My views folder structure looks like this;
- views
-- admin
- index.php
- view
-- index.php
Ideally I want my URLs to look like this, and throw 404 errors where they don't.
example.com/admin/view/form/123
example.com/admin/update/form/123
example.com/admin/delete/form/123
You can do this by several ways.
The fastest way is by creating routes like this:
$route['admin/view/form/(:num)'] = "Admin/view/$1";
When typing exemple.com/admin/view/form/9 , it will redirect to the controller admin, function view and the "9" will be the parameter $form_submission_id
The same thing for routes below.
$route['admin/update/form/(:num)'] = "Admin/update/$1";
$route['admin/delete/form/(:num)'] = "Admin/delete/$1";
of course you could create a function for each one, view, update, delete ... etc
It's normal that you see error when you enter example.com/admin/view because the view function take 1 parameter $form_submission_id

CodeIgniter - URL routing for more cases

Here is what I want to achieve:
https://www.example.com/properties
https://www.example.com/properties/properties-in-newyork
https://www.example.com/properties/properties-in-DC/property-for-rent
https://www.example.com/properties/all-cities/property-for-rent
https://www.example.com/properties/all-cities/property-for-sale
All above is for search. Now I want to get details page like:
https://www.example.com/properties/2br-apartment-for-sale-100
I want to differentiate between search and details page links. Here is what I tried:
$route['properties/index'] = 'properties';
$route['properties(/:any)'] = 'properties/property_details$1';
How can I differential which URL is for properties/property_details function and which URL is for properties/index function?
enter image description here
Set your route.php like this :
$route['properties/index'] = 'properties';
$route['properties'] = 'properties/property_details';
$route['properties/(:any)'] = 'properties/property_details/$1';
Access url :
this direct you index method
https://www.example.com/properties/index
this will direct you property_details method
https://www.example.com/properties/
Controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Properties extends CI_Controller {
public function __construtct()
{
parent::__construtct();
$this->load->helper('url');
}
public function index()
{
echo 'index';
}
public function property_details($component = NULL)
{
echo 'property_details';
echo $component;
}
}
If I'm correct, according to your explanation with differentiating the routes, the problem you are having is, it always running the route for index despite of what your URL having after properties.
You may try it by changing the order of the routes like this;
$route['properties(/:any)'] = 'properties/property_details/$1';
$route['properties/index'] = 'properties';
It always works according to the order of the routes you have placed. If there are acceptable parameters, for the program, properties/index is also something similar to properties(/:any). So, to differentiate between these two, we have to change the order of the routes like this.

Block access to functions in Code Igniter

I'm developing a application in Code Igniter and a problem come by:
I have several functions that access the database, that are routed like this:
controller/function/variable
employess/deleteEmployee/4
So, anyone that put this on the url gonna delete the employee.
How can I manage to allow only a logged admin user to access this functions?
Is there a simple and well accepted way?
I must check every time if there is a user logged in and this user have the permission?
Regards,
Here is the URL for the reference...
https://ellislab.com/codeigniter/user-guide/general/hooks.html
Here is the simple example
Copy this piece of code as checksession.php and save it in /application/hooks
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Checksession
{
private $CI;
public function __construct()
{
$this->CI =&get_instance();
}
public function index()
{
if($this->CI->router->fetch_class() != "login"){
// session check logic here...change this accordingly
if($this->CI->session->userdata['userid'] == '' ){
redirect('login');
}
}
}
}
Copy this code in /application/config/hooks.php
$hook['post_controller_constructor'] = array(
'class' => 'checksession',
'function' => 'index',
'filename' => 'checksession.php',
'filepath' => 'hooks'
);
Enable hooks in /application/config/config.php
$config['enable_hooks'] = TRUE;
Hope this helps.
Good Luck and Happy Coding

CI routing issue

i am currently learning CI and i have come to an issue that i cant seem to solve.
i set up my wamp server in a drive and inside the www(root) folder i have extracted the codeigniter files.
![example][1][1]: http://i.stack.imgur.com/7RKqG.png
then I created my php files for view/model and controller and set the default route in the config/routes.php
so now when I go to my browser and type localhost I get the post.php displayed without anyissue.
but I am unable to access any of the views from here. for example i have a new_post.php view and when i type in the address bar localhost/new_post.php i get a "Not Found
The requested URL /new_post.php was not found on this server." error.
what am i doing wrong? below i have posted the code which i have written in the post.php controller along with a image of the file structure/names i have.
posts.php - controller
<?php
class Posts extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('post'); //loads the post model u created in the models folder
}
function index() //goes to this function 1st when u access the controller
{
$data['posts']=$this->post->get_posts(); // load all the data from the get_posts function in post model to the data array posts
$this->load->view('post_index', $data); //loads the view
}
function post($postID)
{
$data['post']=$this->post->get_post($postID);
$this->load->view('post', $data);
}
function new_post()
{
if($_POST)
{
$data=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' =>1
);
$this->post->insert_post($data);
redirect(base_url(). 'posts/');
}
else
{
$this->load->view('new_post');
}
}
function editpost($postID)
{
$data['success']=0;
if($_POST)
{
$data_post=array(
'title'=> $_POST['title'],
'post'=> $_POST['post'],
'active' => 1
);
$this->post->update_post($postID,$data);
$data['success'] =1;
}
$data['post']=$this->post->get_post($postID);
$this->load->view('edit_post',$data);
}
function deletepost($postID)
{
$this->post->delete_post($postID);
redirect(base_url(). 'posts/');
}
}
![structure][1] [1]: http://i.stack.imgur.com/SnsbW.png
In CodeIgniter you have to use controller to get access to his function
you are saying "when i type in the address bar localhost/new_post.php i get a Not Found" because you try to direct access its function name you have to use example.com/controllername/functionname like this
http://localhost/posts/new_post
for more information check codeignier url
https://ellislab.com/codeigniter/user-guide/general/urls.html
if you not removed index.php using .htaccess then you have to use your url like this
http://localhost/index.php/posts/new_post
In CodeIgniter, everything runs through the main "index.php" file, in your root directory.
So, you would access your new post page, like this;
http://localhost/index.php/posts/new_post
Have a read through the CodeIgniter user guide, it will answer any problem you have.
https://ellislab.com/codeigniter/user-guide/

Codeigniter Route url parents page and child page

Edit: I am new Codeigniter I am not how to use Codeigniter Routing. I create Contact Us page and Map page. Map page is the subpage of Contact Us page.
Table Name : Pages
id label link parent
1 Contact Us contact-us 0
3 About Us about-us 0
2 Map map 1
Here my Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Page extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('page_model');
}
public function index()
{
$data['getAllPage'] = $this->page_model->getAllPages();
$this->load->view('page_listing',$data);
}
public function view($id) {
$data['single_page'] = $this->page_model->displaySinglePage($id);
$this->load->view('single_page',$data);
}
}
In routes.php I have put $route['(:any)'] = "page/view/$1";
When I enter url "http://mytest.dev/contact-us/" or "http://mytest.dev/about-us/" it show correct content of Contact page but I enter "http://mytest.dev/contact-us/map" it still show content of Contact page.
What I want when I enter "http://mytest.dev/contact-us/map" it shuold show content of Map page
Thanks in advance.
Please try code maybe can help
// Parents and Child page.
$route['page/(:any)/(:num)'] = "page/view/$1/$2";
// For Main Home Page.
$route['(:any)'] = "page/view/$1";
I think following routes should work
$route['contact-us'] = 'page/view/$1';
$route['contact-us/map'] = 'page/view/$2';
when you'll echo $id in view method.
"http://mytest.dev/contact-us/" will print $1
and
"http://mytest.dev/contact-us/map" will print $2
Hope this solution will help.
My site has a main 'events' page and an 'events/calendar' page. Create the pages as separate views and then create a function for each sub page in the main controller. Here's my Events controller. If you want a dynamic page you can add the appropriate code in the function.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Events extends CI_Controller {
public function index()
{
$this->load->view('inc/header.php');
$this->load->view('events_view');
$this->load->view('inc/footer.php');
}
public function calendar()
{
$this->load->view('inc/header.php');
$this->load->view('calendar_view');
$this->load->view('inc/footer.php');
}
}

Categories