solodesigner solodesigner - 5 months ago 16
HTML Question

Using PHP conditional statements to switch HTML content on different pages

I'm a front-end developer who is somewhat familiar with but rarely uses PHP. I'm working on a personal project where I'm mostly just using includes to link PHP files together. Here is my overall basic page structure:

<?php include('header.php'); ?>
<?php include('pagetitle.php'); ?>

Page content goes here.

<?php include('footer.php'); ?>


On pagetitle.php, I have an
<h1>
,
<h2>
and background image relating to which page you're on.

My question is, how do I use conditional statements to put all the page titles/subheadings on pagetitle.php and have them switch depending on what page you're on? So for example, I want

<div id="about">
<h1>About</h1>
<h2>About page subheading</h2>
</div>


to show up on about.php, and

<div id="contact">
<h1>Contact Me</h1>
<h2>Contact page subheading</h2>
</div>


to show up on contact.php, etc. etc. ...but only using pagetitle.php on those pages.

The site isn't huge. It would have no more than 10 pages. Also, I do realize I can just use that page title segment on the respective page, but if possible, I want to try this out.

Thanks!

Answer

On your pagetitle.php you could do something like this

<?php

$scriptname = basename($_SERVER["PHP_SELF"]); 

if ($scriptname == "about.php") {
     echo "<h1>About Page</h1>";
}else if($scriptname == "contact.php"){
    echo "<h1>Contact Us</h1>";
}

?>