CyberJunkie
CyberJunkie

Reputation: 22684

Codeigniter if URL segment is missing

Having found out that 3rd URL segments can be passed directly to the a function's parameter I did the following.

URL example:

http://www.mysite.com/profile/user/64

Function in profile controller:

function user($user_id) //$user_id is 3rd URL segment
{
   //get data for user with id = $user_id
}

Using $this->uri->segment(3) returns FALSE is no segment exists. With the function parameter I get

Missing argument 1

How can I return FALSE and not execute the function if the 3rd URL segment is missing? I'm looking for a simple solution without if statements, if possible.

Upvotes: 3

Views: 8419

Answers (4)

antelove
antelove

Reputation: 3358

if ($this->uri->segment(3)) {
  return true
} else {
  return false
}

Upvotes: 0

broadband
broadband

Reputation: 3498

You could also use this:

 public function user($id = null)
 {
   if(!isset($id))
     exit();

   // get data for user with id = $id
 }

or this

public function user()
{
  if( ! $this->uri->segment(3) )
    exit();

  // get data for user with id = $id
}

Upvotes: 2

Alfonso Rubalcava
Alfonso Rubalcava

Reputation: 2247

You get "Missing argument 1" because the function does not get the argument.

Try

function user(){
    if($this->uri->segment(3)){
        //get data for user with id = $this->uri->segment(3)
    }
}

Upvotes: 4

cwallenpoole
cwallenpoole

Reputation: 82058

What about default arguments:

function user($user_id = FALSE) //$user_id is 3rd URL segment
{
   //get data for user with id = $user_id
}

Upvotes: 3

Related Questions