ID the Body Based on URL

Avatar of Chris Coyier
Chris Coyier on
<?php
	$url = explode('/',$_SERVER['REQUEST_URI']);
	$dir = $url[1] ? $url[1] : 'home';
?>

<body id="<?php echo $dir ?>">

This would turn http://domain.tld/blog/home into “blog” (the second level of the URL structure). If at the root, it will return “home”.

Here is an alternate method:

<?php
       $page = $_SERVER['REQUEST_URI'];
       $page = str_replace("/","",$page);
       $page = str_replace(".php","",$page);
       $page = str_replace("?s=","",$page);
       $page = $page ? $page : 'index'
?>

This would turn http://domain.tld/blog/home into “domaintldbloghome”, which is far more specific. It also will remove “.php” file extensions and the default WordPress search parameter.

More Secure Method

function curr_virtdir($echo=true){
        $url = explode('/',$_SERVER['REQUEST_URI']);
        $dir = $url[1] ? $url[1] : 'home'; // defaults to this if in the root
        $dir = htmlentities(trim(strip_tags($dir))); // prevent injection into the DOM through this function
        if ($echo) echo $dir;
        return echo $dir; // ie. curr_virtdir(false)
}
function get_curr_virtdir(){
        curr_virtdir(false);
}

Returns the “middle” directory value:

On https://css-tricks.com it would return “home
On https://css-tricks.com/snippets it would return “snippets
On https://css-tricks.com/forums/viewforum.php?f=6 it would return “forums

The strip_tags() and htmlentities() functions prevent malicious code from being insterted into the URL and ran, e.g.

<body id="foo"><script>alert("Booo");</script>

Usage for IDing the body:

<body id="<?php curr_virtdir(); ?>">

Other usage:

<?php
  if ( get_curr_virtdir() == "store" ){
    echo "Welcome to our awesome store !";
  } elseif ( get_curr_virtdir() == "home" ){
    echo "Welcome home :-)";
  } else {
    echo "Welcome on some other page";
  }
?>