Kate
Kate

Reputation: 89

If url is the homepage (/ or index.php) do this

I'm trying to hide some content on my homepage using this code:

<?php   

  $homeurl = 'index.php';                               
  $homepage = "/";
  $currentpage = $_SERVER['REQUEST_URI'];

  if($currentpage == $homepage or $currentpage == 'index.php') {
  echo 'no content';
  } else {
    echo 'content';
  }                                     

?> 

It works if the url is simply www.mysite.com but not if the url is www.mysite.com/index.php - I need the content hidden in both instances. My PHP is very basic so please forgive me!

Upvotes: 5

Views: 17586

Answers (3)

A. Genedy
A. Genedy

Reputation: 718

Google seems to keep old SO pages afloat, so excuse my late reply :) I think a better solution to detect if we're on the homepage is something like this:

function isHomepage() {
  $page = basename($_SERVER['PHP_SELF']);
  return $page === 'index.php';
}

The above code would work whether placed in the homepage file itself or in some included page (unlike __FILE__) and it would also work if the URL of the page doesn't explicitly have index.php in it, for example http://example.com/app/ would still work correctly.

However, if you're using routing and index.php is the entry page for your controllers, the above would always return true. In that case you should parse $_SERVER['REQUEST_URI'] instead.

Upvotes: 0

Lkopo
Lkopo

Reputation: 4835

So you need add / before index.php too:

$homeurl = '/index.php';

Your solution of detecting index looks a bit weird, but there is not enough code (for example frontend) to help with.

Upvotes: 4

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

You can just use the PHP magic constant and basename()

echo basename(__FILE__);

Here is the logic;

if( basename(__FILE__) == "index.php" ) {
  //Hide content
} else {
  //Show content
}

For example;

http://localhost/test/
index.php

http://localhost/test/index.php
index.php

Upvotes: 1

Related Questions