Steve Kim
Steve Kim

Reputation: 5611

How to know what is the current url in php

So, what is the conditional logic to check a certain href url? For example, there are three specific pages.

Then what do I write to check if the current page is equal to the specific url:

 <?php if () { ?> <!--if the current page is equal to `page_1` -->   
   <span>Show Page 1</span>
 <?php } elseif () { ?> <!--if the current page is equal to `page_2` -->
   <span>Show Page 2</span>
<?php } elseif () { ?> <!--if the current page is equal to `page_3` -->
   <span>Show Page 3</span>
<?php } else { ?> <!--if the current page is not equal to any -->
    <span>Show Random</span>
<?php } ?>

Upvotes: 0

Views: 58

Answers (3)

Đức Tiến
Đức Tiến

Reputation: 31

you can use this

$getlink=explode("/",$_SERVER['REQUEST_URI']);
//this will return an array of the url.
$1st = $getlink[1];
//get the page_* then use this var for your condition
if($1st == 'page_1'){
  echo '<span>'.$showpage1.'</span>';
}// and go on...

hope this can help :)

Upvotes: 1

Vishal Kacha
Vishal Kacha

Reputation: 26

explode url with ".com/" then check the condition.check below code.
`enter code here`
 1. <?php  $url = "http://example.com/page_1";
       $url_ex = explode(".com/",$url);
          print_r($url_ex);
 2. Result = Array ( [0] => http://example [1] => page_1 )
 <?php if ($url_ex[1] == 'page_1') { ?> <!--if the current page is equal to `page_1` -->   
   <span>Show Page 1</span>
 <?php } elseif ($url_ex[1] == 'page_2') { ?> <!--if the current page is equal to `page_2` -->
   <span>Show Page 2</span>
<?php } elseif ($url_ex[1] == 'page_3') { ?> <!--if the current page is equal to `page_3` -->
   <span>Show Page 3</span>
<?php } else { ?> <!--if the current page is not equal to any -->
    <span>Show Random</span>
<?php } ?>

Upvotes: 1

Ormoz
Ormoz

Reputation: 3011

You can use the following function:

if(CurrentPageURL()=='http://example.com/page_1'){
 /*Your code*/
}
function CurrentPageURL()
{
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}

Upvotes: 1

Related Questions