简体   繁体   中英

get uri segments from default controller codeigniter

i have codeigniter setup to use "home" as the default controller which is to display homepage i tried to run the index function within home controller to collect the uri segments to determine whether or not to redirect or display home page but it seems to think that the uri segment is another controller mysite.com/segment1

function index(){
    $url1 = $this->uri->segment(1);
    if(!empty($url)){
        echo $url1;
    }
    else{
        $this->load->view('home_page');
    }
} 

You are setting $url1 as the segment then testing if $url is empty or not. From your code, $url will always be empty.

Make sure you keep an eye on what you call your variables.

So what you have now...

function index(){
    $url1 = $this->uri->segment(1);
    if(!empty($url)){ // $url will always be empty as it's not defined.
        echo $url1;
    }
    else{
        $this->load->view('home_page');
    }
}

What you should have...

function index(){
    $url = $this->uri->segment(1);
    if(!empty($url)){
        echo $url;
    }
    else{
        $this->load->view('home_page');
    }
}

Then it will do as you intended.

You can set default controller to home. Then to be able to read $this->uri->segment(3); you nead to pass thet uri via URL mysite.com/controller/function/uri-segment(3). If you hav an Index function in home controller mysite.com and you want to pass a value of 11 via uri your url shuld look like this:

mysite.com/home/index/11

For this to work i had to change the routes to

$routes[('any')] =  "New_controller"; //created a new controller 

in "New_controller" i could then define the first segment i want to get

   function index(){
    // define segments
    $url = $this->uri->segment(1);
     if(!empty($url)){
      echo $url;
    }

and of course my

$routes['default_controller'] = "home";


function index(){

// home controller
 $this->load->view('home_page');


} 

Now when i go to mysite.com it takes me to the homepage or if i go to mysite.com/12345 it takes me to the new controller page where i can run a query on the segment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM