Home » Php » php – If this Page Show This Else Show This

php – If this Page Show This Else Show This

Posted by: admin July 12, 2020 Leave a comment

Questions:

On all pages apart from the contact page, I want it to show the following in the inc-header.php include.

<p><a href="contact.php">Contact</a></p>

On the page contact.php, I want it to show:

<p><a href="index.php">Home</a></p>

This should be possible correct?

How to&Answers:
<?php
if (stripos($_SERVER['REQUEST_URI'], 'contact.php')){
     echo '<p><a href="index.php">Home</a></p>';
}
else{
     echo '<p><a href="contact.php">Contact</a></p>';
}

Answer:

if ($_SERVER["SCRIPT_NAME"] == '/contact.php') {
    echo '<p><a href="index.php">Home</a></p>';
} else {
    echo '<p><a href="contact.php">Contact</a></p>';
}

Answer:

There is a global variable named $_SERVER['PHP_SELF'] that contains the name of your page currently requested. Combined with basename() this should work:

if( basename($_SERVER['PHP_SELF'], '.php') == 'contact' ) {
    // Contact page
} else {
    // Some other page
}

Answer:

the quick and dirty solution is:

<?php
$current_page = 'contact';
include('inc_header.php');
....
?>

In inc_header.php:

<?php
if($current_page == 'contact') {
    // show home link
} else {
    // show contact link
}
?>

Answer:

You can do it with a simple if statement, but this will only work for your contact page. You could also use a simple function in your inc-header file that would work like so:

function LinkToPageOrHome( $script, $title ){
   if ( strtolower( $_SERVER[ 'SCRIPT_NAME' ] ) == strtolower( $script) ){
       $script = 'home.php';
       $title = 'Home';
   }
   echo '<p><a href="' . $script. '">' . htmlentities( $title ) . '</a></p>';
}

It’s sort of a blunt approach from a design standpoint, but you could use LinkToPageOrHome( 'page.php', 'My Page' ); in multiple templates and never worry about having a page link to itself.