3

I am trying to check with PHP if the user is on some specific pages. Currently I am doing it like this:

<?php if($_SERVER['REQUEST_URI'] == "/forum/"){echo "class='active'";} ?>

Although, this only works if the URL is http://example.com/forum/

How can I make the above code works, on both /forum/ but also on /forum/??

Example:

http://example.com/forum/anotherpage
oliverbj
  • 5,771
  • 27
  • 83
  • 178

1 Answers1

6

You can use a startswith function (see this stackoverflow post: startsWith() and endsWith() functions in PHP). Here, you test would be:

if (startsWith ($_SERVER['REQUEST_URI'], '/forum/'))

You can also use a regexp: http://php.net/manual/en/regex.examples.php. Here, your test would be:

if (preg_match ('#^/forum/#', $_SERVER['REQUEST_URI']))

Hope this helps.

Community
  • 1
  • 1
Niols
  • 627
  • 1
  • 4
  • 13
  • That works perfectly! (Used the preg_match solution). Question: What's the #^ before /forum/ representing) – oliverbj Mar 01 '15 at 16:31
  • `#` is the regexp delimiter. It can be anything (often `#` or `/`, but you need to escape this delimiter in the regexp, so `/` isn't really good there). `^` mean *begining of the string*. – Niols Mar 01 '15 at 16:31
  • I'd advice against using regex for this especially if you need to check multiple URLs it will be a performance killer compared to other solutions. – Tom Tom Mar 01 '15 at 16:35
  • @TomToms Would you advise "startsWith"? – oliverbj Mar 01 '15 at 16:45
  • If you just need it for one url yes, for multiple I would use an explode(). – Tom Tom Mar 01 '15 at 16:46