phprequest-uri

How to check if url is the homepage


Found this answer If url is the homepage (/ or index.php) do this which was really helpful however doesn't fully answer my question.

I have an index of site for school that shows all my folders to different assignments. so my homepage is actually domain/folder/index.html

so when I ask if $currentpage == /midterm/index.php || /midterm/ it always triggers as true even if I am on /midterm/add.php

<?php
$homeurl = '/midterm/index.php';
$homepage = '/midterm';
$currentpage = $_SERVER['REQUEST_URI'];

if ($currentpage == $homeurl || $homepage) {
    echo '<div class="hero"></div>';
}

Solution

  • Your problem is in your conditional: if ($currentpage == $homeurl || $homepage) will always return true because you are stating that $currentpage must equal $homeurl, OR just simply $homepage. Adding brackets helps showcase this:

    if ( ($currentpage == $homeurl) || ($homepage) )
    

    Because $homepage is set, it's truthy, and evaluates to true. Because only one part of the conditional needs to be true due to your OR (||), the condition returns true as a whole.

    To resolve this, you're looking to check whether $currentpage is equal to $homeurl OR $currentpage is equal to $homepage:

    if ($currentpage == $homeurl || $currentpage == $homepage)
    

    Which, with added brackets, evaluates to:

    if ( ($currentpage == $homeurl ) || ($currentpage == $homepage) )
    

    Hope this helps! :)