Félix Desjardins
Félix Desjardins

Reputation: 3223

Check if URL = Desired URL (PHP)

I'm trying to check if the current URL equals the desired URL for making the link class active (Bootstrap).

Example

<?php
    If ($currenturl = "show.php?name=123") {
      ?><li class="active"><a href="show.php?name="123"">123</a></li><?php
    }else{
        ?><li class=""><a href="show.php?name="123"">123</a></li><?php
    }
?>

Current URL -> $currenturl = $_SERVER['REQUEST_URI']

Now, I have this if I'm on show.php?name=456

see

Upvotes: 1

Views: 2080

Answers (2)

Kevin
Kevin

Reputation: 41885

Make sure you have the correct comparison inside the if. You're currently using the assignment operator:

Note the difference:

if($currenturl = "show.php?name=123") // assignment =
  // changes $currenturl to "show.php?name=123"
  // and then tests if("show.php?name=123") equivalent to if(true)
  // see also http://stackoverflow.com/questions/5940626/evaluation-of-assignment-in-php

if($currenturl == "show.php?name=123") // comparison ==

Second: You have set $urlpage but comparing $currenturl. Use $urlpage

Code:

<?php $urlpage = $_SERVER['REQUEST_URI']; ?>
<?php if ($urlpage == "/show.php?nom=123") { ?>
    <li class="active"><a href="/show.php?nom=123">123</a></li>
<?php } else { ?>
    <li class=""><a href="/show.php?nom=123">123</a></li>
<?php } ?>

An alternative using a ternary operator:

<li <?php echo ($urlpage == "/show.php?nom=123") ? 'class="active"' : ''; ?>><a href="/show.php?nom=123">123</a></li>

Applying to all pages:

<?php $pages = array('123', '456', '789'); ?>
<ul>
    <li <?php echo (!isset($_GET['nom']) ? 'class="active"' : ''); ?>><a href="show.php">Home</a></li>
    <?php foreach($pages as $page): ?>
        <?php if (isset($_GET['nom']) && $_GET['nom'] == $page) { ?>
            <li class="active"><a href="/show.php?nom=<?php echo $page; ?>"><?php echo $page; ?></a></li>
        <?php } else { ?>
            <li class=""><a href="/show.php?nom=<?php echo $page; ?>"><?php echo $page; ?></a></li>
        <?php } ?>
    <?php endforeach; ?>
</ul>

Upvotes: 4

DdD
DdD

Reputation: 453

An alternate way is to use the $_GET

if(isset($_GET['name']))
 if($_GET['name'] == '123') 
  ...

and so forth

Upvotes: 0

Related Questions