0
votes

I just started working with CodeIgniter and I am having some trouble with the segment-based urls. I understand how to call them doing $variable = $this->uri->segment(2); but whenever I go to the url, I am getting a 404. Is there something I need to do for URI routing?

For example, I am trying to go to localhost/ci/index.php/games/1000 (where 1000 would be a game ID), but I am getting a 404. localhost/ci/index.php/games/ works fine.

2
Don't know about CodeIgniter but the url need s either a / to signify directory at the end or a file extension eg. .php. - Zac
@Zac No, that's not how uri segments work (and it's not only something CI do): if you note there's 'index.php', so those cannot be directories. - Damien Pirsy
Apologies, thanks for setting me straight...Everyday's a day at school! - Zac

2 Answers

3
votes

In order for that to work you would need to have a controller called games.php with this content

class Games extends CI_Controller
{
    public function index($id)
    {
        echo $id;
    }
}

Unless you do something like this

class Games extends CI_Controller
{
    public function index()
    {
        echo 'this is index';
    }
    public function game($id)
    {
        echo $id;
    }
}

and add this to your routes.php

$route['game/(:any)']  = "games/game/$1";
2
votes

By default the 2nd segment of the URI is a method (function) within the controller which CI automatically calls.

So in your case you are actually attempting to call a function named 1000() within the games controller, which doesn't exist and therefore results in a 404.

Instead what I think you want to do is call the index() function, and pass the variable 1000 to it.

So if you were to go to localhost/ci/index.php/games/index/1000 you shouldn't get a 404 anymore, however your URI segment will now be wrong to get the variable 1000.

Here is a working example of the controller with the corrected URI segment:

class Games extends CI_Controller
{
    // good habit to call __construct in order to load 
    // any models, libraries, or helpers used throughout this controller
    public function __construct() 
    {
        parent::__construct();
    }

    // default controller
    public function index()
    {
        // this should display 1000
        echo $this->uri->segment(3);
    }
}