4

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

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That works perfectly! (Used the preg_match solution). Question: What's the #^ before /forum/ representing)
# 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.
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.
@TomToms Would you advise "startsWith"?
If you just need it for one url yes, for multiple I would use an explode().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.