Detecting Current Page with PHP

Sometimes, it is necessary to get the current page the visitor is on and then feed it through some other code so that it can produce a result based on the current page.

 

For this site, we gather what page is displayed, then based on that result, the output is put into the menu so that it displays the current page class in the <li> tag and then turns the current page text green in the nav menu.

 

<? function curPageURL() {
$pageURL = 'http';  if ($_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; }
?>

 

We then give the result a variable name so that we can call it further down the page.

 

<? function curPageName() {

return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1); }

$page = curPageName(); ?>

 

Based on the result, we then serve up the correct class for the current page to turn the text green. In this case, it is looking for the home page and if present, setting the active class to home.

 

<?php if ($page == "index.html") {
echo" class=\"active home\"" ; 
} else echo "" ;?>

Comments are closed.