Search code examples
phpif-statementhtmldetect

PHP - Detect homepage in template of script?


How to detect home page in php from main index.php of script. So I have that script. This script is main page of script (not template's index.php

<?php

$view->title = $LANG["HOMEPAGE_TITLE"];
$view->description = $LANG["HOMEPAGE_DESCRIPTION"];
$view->keywords = $LANG["HOMEPAGE_TAGS"];

if ($view->nav == 'homepage') {
    // ONLY FOR HOME PAGE
    $view->header = $view->render(DIR_TEMPLATE.WEBSITE_TEMPLATE.'/header.php');
    $view->footer = $view->render(DIR_TEMPLATE.WEBSITE_TEMPLATE.'/footer.php');
} else { 
    // FOR OTHER ALL PAGE
    $view->header = $view->render(DIR_TEMPLATE.WEBSITE_TEMPLATE.'/header-common.php');
    $view->footer = $view->render(DIR_TEMPLATE.WEBSITE_TEMPLATE.'/footer-common.php');
}

echo $view->render(DIR_TEMPLATE.WEBSITE_TEMPLATE.'/index.php'); //This file home page file

I have enter this code but it doesn't detect home page And I have put this code to index.php (home page). How can I detect is homepage? I have put nav id but it also could not detect.

<?php echo $header;?>  
//HOME PAGE CONTENT 
<?php echo $footer;?>

Solution

  • I have come across the same scenario while doing a project. This worked for me.

    <?php
    
    $current_file=  explode('/', $_SERVER['SCRIPT_NAME']);
    $current_file=  end($current_file);
    
    if($current_file=='index.php'){
     // YOUR LOGIC FOR HOME PAGE
    } else {
     // YOUR LOGIC FOR ALL OTHER PAGE
    }
    
    ?>
    

    What this script basically does is it will split the url of the form

    http://www.somewebsite.com/index.php

    which is provided by

    $_SERVER['SCRIPT_NAME']
    

    The splitting is done by the character ' / '.

    So the result will be an array of strings.

    http , ' ' , www.somewebsite.com , index.php

    We are then checking if the last component of the array is "index.php".

    This way we are detecting whether the page is home page or not.