Sunday, January 2, 2011

PHP Syntax for Header/footer and other simple things.

I often hear that people find it hard to learn PHP as they are also learning html, graphic design javascript and probably a dozen other things at a time. Instead they decide to put it off and not use it at all. Rather than learning all of PHP I have listed below some of simple PHP syntax that any website designer cant live without. PHP is very easy to learn and once you get the hang of it you won't be able to live a day without it.


*For all of my tips, make sure you change all your pages to a .php extension rather than a .html extension . Don't worry, all of your HTML will continue to work*


Tired of changing the header and footer on every page of your site. Use the below syntax.

<?php
require_once("headertemplate.php"); //path to your header template html file
?>
 Your html content goes here

<?php 
require_once("footertemplate.php"); //path to your footer template html file
?>
This is pretty straight forward. Whenever you have a require_once(); that puts that file in its place. To make this a little more useful I will also show you how to put the title into your HTML file.


MyPage.php
<?php
$title = "This is the title";
require_once("headertemplate.php"); //path to your header template html file

?>
 Your html content goes here


<?php 
require_once("footertemplate.php"); //path to your footer template html file

?>

headertemplate.php
<html>
<header><title><?php echo $title; ?></title>...
 As you can see I set the title variable in MyPage.php and the I outputted it in my template.

The last thing I think an HTML developer cant live without is the following for updating your copyright notices.


<?php
$time = time();
$year =  date("Y", $time);
echo "Copyright 2001 - $year";
?>
  
 Now you no longer have to edit the year on all of your copyright notices. In addition, you won't have to change every page to change a link or a color on your site.