Jason
Jason

Reputation: 51

CodeIgniter PHP: how to echo a URL segment only if that segment actually exists

OK, I've been trying to figure this one out for 3 days, but I can't seem to get it right. I'm trying to conditionally echo a URL segment (the page number) only if that segment actually exists for the particular webpage. Specifically, I'm dealing with the canonical tag in my header template.


THE BACKGROUND:

My current code echos paginated directory pages as desired, like this:

 https://www.example.com/subjects/apples/2
 https://www.example.com/subjects/apples/3
 https://www.example.com/subjects/apples/4
 etc.

It echos directory home pages as NOT desired, like this:

 https://www.example.com/subjects/apples/


WHAT MUST STAY THE SAME:

Paginated directory URLs do NOT end with a forward slash, which is good.


WHAT MUST CHANGE:

Directory home pages DO end with a forward slash, which is bad.


THE EXISTING CODE:

<link rel="canonical" href="<?php echo $this->config->item("base_url");?><?php echo $category_in_url;?>/<?php echo $this->uri->segment(2);?>" />


THE DESIRED OUTCOME:

Directory home pages must NOT end with a forward slash. To stop leaving behind an orphaned forward slash at the end of directory home page URLs, your new code will echo

/<?php echo $this->uri->segment(2);?>

only if segment 2 (i.e., a page number of 2+) actually exists for the particular webpage. Pages 0 and 1 do not receive a page number in the URL. So, starting with Page 2, I need to echo that part. Paginated directory pages should look like this:

https://www.example.com/subjects/apples/4

Directory home pages should look like this:

https://www.example.com/subjects/apples


NOTE: Your solution has to work with my existing code without breaking the PHP.

Thank you in advance for your much-appreciated help!

Jason

Upvotes: 0

Views: 396

Answers (1)

Mikeyhun
Mikeyhun

Reputation: 256

<link rel="canonical" href="<?php echo $this->config->item("base_url");?><?php echo $category_in_url.((int)$this->uri->segment(2,0) > 1 ? '/'.$this->uri->segment(2) : '');?>" />

Upvotes: 1

Related Questions