Codeigniter routes for passing get parameter to index function - php

I have a url www.mywebsite.com/store/123456
where store is my controller class and I have a index function in it where Im getting the value after after store ,ie 123456.But im not able to achieve it.
As found online,I have tried adding this to routes $route['store/(:any)'] = 'store/index'; also tried
$route['store/(:any)'] = 'store/index/$1';
but doesn't seem to work.Please help me out.
In controller index function is
public function index()
{
echo $this->uri->segment(1);
}
But its not working.Pleae help

You are invoking 123456() method instead of index() method therefore you get CI's 404.
The simplest way is to use this kind of route
$route['store/(:any)'] = 'store/index/$1';
AND in top of it add parameter to index function in your case
public function index($parameter)
{
echo $this->uri->segment(2);
}
note that I changed segment parameter please see documentation.
using _remap()
function _remap($parameter){
$this->index($parameter);
}
function index($p)
{
echo $p; //shows 123456
}

If I remember correctly:
segment(n) gives you the segments of your uri before the routing takes place
rsegment(n) gives you the segments of your uri after routing (if routing occurred or the same as segment if it didn't)
so for /store/123456 getting rerouted to /store/index/123456
segment(1) == rsegment(1) == 'store'
rsegment(2) == 'index'
segment(2) == rsegment(3) == '123456'

Route:
$route['terms_and_conditions'] = 'SO_front/page/1';
controller :
public function page($id)
{
echo $id;
}
Output :
1

Here my solution for CI3...i would prefer laravel for advanced routing, orm,restapi, build in vuejs.
$route['store/(:any)'] = 'store/index/';
public function your index(){
$parameter=$this->uri->segment(2);
//use parameter for sql query.
}
Let say your route $route[store/product/update/(:any)] , then $parameter=$this->uri->segment(4)
Problem?. You will need to change entire file code if you plan to change the route name include view, controller, and custom route.

Related

Is using if else statement to load view based on parameters after controller and action part of url efficient or is there a better way of doing this

I can have the following urls
www.example.com/accounts/
www.example.com/accounts/signup
www.example.com/accounts/signup/validate
www.example.com/accounts/login
for each case, accounts becomes my controller, and index, signup, signup and login becomes my actions (or methods) respectively. I have to render different views based on what my actions are. Here is an example of what my code looks like
index
$url_segments = explode('/', $url);
$controller = !empty($url_segments[0]) ? $url_segments[0] : 'home';
array_shift($url_segments); // removes the controller name from array
$action = isset($url_segments[0]) && !empty($url_segments[0]) ? $url_segments[0] : 'index';
array_shift($url_segments); // removes the action name from array
$controller = ucfirst($controller);
$controller = new $controller($url_segments);
$controller->$action();
controller class
class Accounts{
private $url_segments;
public function __construct() {
$this->url_segments = $url_segments;
}
public function index() {
// index code here
}
public function login() {
// login code here
}
public function signup() {
if (!isset($this->url_segments[0])) {
// url entered was: example.com/signup
} else if (isset($this->url_segments[0]) && $this->url_segments[0] == 'validate') {
// url entered was: example.com/signup/validate
}
}
}
from how my code appeared above, it can be seen that as parameters keep adding after the controller and action part of the url I'll need to keep using conditional statements to run the proper code as in the case of /signup/ and signup/validate. Is this method of using conditional statement to load view based on parameters efficient or is there a better way of doing this.
I would recommend you to make use of a routing system like Symfony Routing. There you could add a new Route for every url and redirect them to your specific controller.
Example Route:
$routes = new RouteCollection();
$routes->add('/accounts_signup', route('POST', "/accounts/signup", 'App\Controller\AccountController:signup'));
return $routes;
This route would call the signup method in the AccountController calss when www.example.com/accounts/signup get called with a post request.
I recommend you to use something like this. Even if this might be a bit complicated for the beginning, after reading (and understanding) the docs this will safe you a lot of time and it will make your code more readable as well.

Redirect user to a self-made 404 page when users input wrong arguments

I'm using Codeigniter version 3.0.6 and now I have a controller named modifyfiles. The index function of this controller accepts an argument.
Using the given argument, the index controller will search a desired data in a model. The following code is my index function :
public function index($id){
$_SESSION['logged_in']['idmod'] = $id;
$this->data['modullist'] = $this->__getmodulbyid($id);
$this->data['lecturelist'] = $this->__getlecturelist();
if(count($this->data['modullist']) <= 0){
show_404();
} else {
$this->load->view($this->layout, $this->data);
}
}
It works very well for now, when I try to insert wrong number arguments it directs me to the codeigniter built-in 404 page.
But when I try to insert some non numbers arguments, say some characters, it directs me to my own 404 page.
Here's my routing rules :
$route['404_override'] = 'home/pagemissing';
$route['dosen/modifymodul'] = 'dosen-tools/modifymodul';
$route['dosen/modifymodul/(:num)'] = 'dosen-tools/modifymodul/index/$1';
I want when users input wrong arguments, no matter they were numbers or characters, the function will redirect to my own 404 page, not the built-in one. How can I achieve that?
I'm pretty sure the problem is in my conditional block
if(count($this->data['modullist']) <= 0){
show_404();
} else {
$this->load->view($this->layout, $this->data);
}
What should I write to replace the show_404() ?
Or if I'm not wrong, how can I replace the show_404() with an 404_override trigger?
Solved
I did a little research and ended up creating this callback in one of my routing rules
$route['dosen/modifymodul/(:num)'] =
function ($id){
if(is_numeric($id)){
return 'dosen-tools/modifymodul/index/'.$id;
} else {
return 'home/pagemissing';
}
};
Thanks everybody

Passing value through url

I am trying to send a url from view page to controller but it does not seem to work the way i am thinking.
View Page
Product
User
I want to get "tbl_product"
Controller admin
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->uri->segment(4);
}
}
?>
but if the segment(4) is changed to segment(3), it shows up with displaying "product" in the screen
your controller function should have arguments for your url segments
for example:
public function test($product = 'product', $tbl = 'tbl_product') {
echo $tbl // contains the string tbl_product
}
Since you said your routes look like this:
$route['default_controller'] = "admin";
$route['404_override'] = ''
and your URL is like this:
<?= base_url() ?>admin/test/product/tbl_product
Then if your base_url() is localhost/my_app, your URL will be read as this:
http://localhost/my_app/admin/test/product/tbl_product
http://localhost/my_app/CONTROLLER/METHOD/PARAMETER/PARAMETER
So in your controller, you can do this:
class Admin extends CI_Controller {
public function test($product = NULL, $tbl_product = NULL) {
echo $product;
echo $tbl_product;
}
}
It's strange to use codeigniter for this purpose, because codeigniter uses as default the url format bellow.
"[base_url]/[controller]/[method]"
I think it will be better and more easy to just pass the values you want as get parameters and make some httaccess rules to make your url more readable for the user and robots. That said you can do that:
Product
<?php
class Admin extends CI_Controller {
public function test() {
echo $this->input->get('product');
//should output 'tbl_product'
}
}
?>
If you prefer to use uri instead u should route your uri's so it will be like.
In your routes file you probably I'll need something like this.
$route['product/(:any)'] = "Admin/test";
This way you will probably access the uri segments correctly.
Thank you so much for going through.
$this->uri->segment(4); // is now working :S
its not working properly after all I made changes to routes.php and came back to default again. I seriously have no idea what the reason behind not displaying the result before.

calling a function in controller from a view and using remap to route in controller

Am not able to call a controller function from my view
This is my view code
echo "<a href='".$base_url."/qst/d/".$row['id']."' class='btn linkcolor'>DENY</a>";
which calls a controller qst and a function deny in it
here is my controller code
public function _remap($method, $params = array()) {
if ($method == 'd') {
$this->deny();
}
}
public function deny($id){
}
am getting the error undefined varaible id.
also am getting Missing argument 1 for qst::d
can anyone tell me what's missing in the code so that it works?
Why not just use routes? In application/config/routes.php, add:
$route['qst/d/(:num)']= 'qst/deny/$1';
Your link only has /d/ for the method name, shouldn't this be /qst/deny/?
EDIT: Also, perhaps you should set a default for the ID and then check to see if the ID is default. (Perhaps null and an is_null check?) Have you var_dump'ed something within the deny method to verify that is the method running?

SEO url gives 404-error in CodeIgniter

I am pretty new to codeigniter. I do know php.
How can I accomplish to load the right view?
My url: /blog/this-is-my-title
I’ve told the controller something like
if end($this->uri->segment_array()) does exist in DB then load this data into some view.
I am getting an 404-error everytime I access /blog/whatever
What am i seeing wrong?
unless you're using routing, the url /blog/this-is-my-title will always 404 because CI is looking for a method called this-is-my-title, which of course doesn't exist.
A quick fix is to put your post display code in to another function and edit the URLs to access posts from say: /blog/view/the-post-title
A route like:
$route['blog/(:any)'] = "blog/view/$1";
may also achieve what you want, if you want the URI to stay as just `/blog/this-is-my-title'
The may be more possibilities:
The most common - mod_rewrite is not active
.htaccess is not configured correctly (if u didn't edited it try /blog/index.php/whatever)
The controller does not exist or is placed in the wrong folder
Suggestion: if you only need to change data use another view in the same controller
if (something)
{
$this->load->view('whatever');
}
else
{
$this->load->view('somethingelse');
}
If none of those works post a sample of code and configuration of .htaccess and I'll take a look.
The best way to solve this problem is to remap the controller. That way, you can still use the same controller to do other things too.
No routing required!
enter code here
<?php
class Blog extends Controller {
function __construct()
{
parent::__construct();
}
public function _remap($method, $params = array())
{
if (method_exists($this, $method))
{
$this->$method();
}
else
{
$this->show_post();
}
}
function index()
{
// show blog front page
echo 'blog';
}
function edit()
{
// edit blog entry
}
function category()
{
// list entries for this category
}
function show_post()
{
$url_title = $this->uri->segment(2);
// get the post by the url_title
if(NO RESULTS)
{
show_404();
}
else
{
// show post
}
}
}
?>

Categories