1

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

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Félix Desjardins
  • 3,223
  • 3
  • 21
  • 36

2 Answers2

4

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>
Kevin
  • 41,694
  • 12
  • 53
  • 70
0

An alternate way is to use the $_GET

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

and so forth

DdD
  • 453
  • 4
  • 19
  • Yes, i change to `If ($_GET['name'] == '123')` but I get an error : `Notice: Undefined index: name in C:\xampp\htdocs\cadeau noel\cadeau.php on line 40`. Line 40 -> `If ($_GET['name'] == '123') {` – Félix Desjardins Dec 08 '14 at 00:38
  • What does URL look like? (In your browser) – DdD Dec 08 '14 at 00:39
  • Also thats why I suggested to put `if(isset($_GET['name']))` if your URL does not have the ?name=123 or name=124, name=125 etc at the end of the URL, it will just give a warning. So either earlier in the code add `if(!isset($_GET['name'])) $_GET['name'] = '';` – DdD Dec 08 '14 at 00:42
  • Tank you, but I used the Ghost answer, it was better. – Félix Desjardins Dec 08 '14 at 01:08