Search code examples
phpcodeignitercodeigniter-routing

How to get CodeIgniter to ignore the last segment entered into the URL-but still keep it there?


I'm using CodeIgniter to build a user profile section from scratch. What happens is, the user will put in the URL:

www.somesite.com/profile/view/<USERNAME>

(profile is the folder & view is the controller)

and I will use IF ELSE statements to check to see if $currentURL (see below) is in the DB and load the required page.

But what's happening right now is it's looking for a function(I think) inside view to execute. But there is none. Which results in a 404 error.

Is it possible for CodeIgniter to ignore the last segment of that URL but still keep it there so that I can use;

$currentURL = $this->uri->segment(3);

to grab the USERNAME?

Thanks for viewing my question,

Lewis.


Solution

  • If I understand you correctly:

    declare your function as follows

    public function view($var1, $username = "") {...}

    where $var1 must be filled in but $username can be ommited and its default value is ""


    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class View extends CI_Controller { //can not belive that View is not reserved word
    
        public function __construct() {
            parent::__construct();
        }
    
        public function index() {
            //index() function can not have parameters
            //redirect('view/show');
            //if no username is set, do default thing like show list of users
            //load view or something
        }
    
        public function show($username = "") {
            //this function can have parameters
            //load views from here
            $this->load->view('abc_view');
        }
    }
    

    Add to routes.php following

    $route['profile/view/(:any)'] = "profile/view/show/$1";

    this will allow you to have nice URL as you expect

    site.com/profile/view/Peterson123

    NOTE when using "routing" method do not redirect(profile/view/show) in index()


    Another aproach that uses _remap() is explained here.