Results 1 to 1 of 1
09-08-2011, 11:03 AM #1
[TUT][PHP+HTML] Simplifying code via Includes
So I've worked with PHP for years now... This tutorial was written by me, and posted on one other forum. This will be part one in a series of tutorials I'm going to write - from the basics (like this one) to more advanced stuff (AJAX, etc) to databases.
What I'm going to cover in this tutorial is how to use PHP with your HTML files, for the main purpose of simplifying coding and easier changes. For this tutorial, I'm going to assume you have a webhost - whether it be on your PC (Xampp, WAMP, etc) or a server/shared host that you're paying for/got for free.
Most hosts include PHP built in. If yours doesn't, you may want a host that's with the times. xD
Ch. 0 - USING PHP
In order to get your server to parse PHP, we're going to need your file to be renamed to .php (NOTE: This is not always mandatory, and you can have PHP parse any file type, but I'll get to that in another tutorial!) after you have your index.php/whatever.php, you need to add your PHP tags.
Another small but important note, and something even I mess up on occasion is that with PHP code, every line (except continued statements - we'll get to that!) must end with a semicolon ( ; ).
Ch. 1 - CODE SIMPLIFICATION VIA INCLUDES
The first thing you want is an HTML file. I'll be providing code snippets all the way through.
So let's start with simplification of code. Let's say you have a navigation bar that you want on every page. Sure, you could copy and paste it to every html file, but what happens when you add a new page? You have to update all your links. This is where includes come in!
Here's our HTML nav bar:
<a href="index.html">Home</a> <a href="aboutus.html">About Us</a> <a href="portfolio.html">Portfolio</a> <a href="contact.html">Contact Us</a>
Open the page and ensure that you see the navigation - view the source, too (Press Control U!) and take note of it.
Now, let's make a new folder in our site's folder. Call it "inc"
In this folder, create a new text file. Rename it to "nav.inc"
In nav.inc, put the whole nav bar code.
Now, delete the navbar HTML from your index.php/whatever.php file. In it's place put
<?php include("inc/nav.inc"); ?>
Does it look similar to the orginal? It should! PHP has included your HTML code into the site. This can be very useful if your code would be hundreds of lines, but your using parts of the same code everywhere. I use it for navigation bars, sidebars, sometimes ads, and footers, mainly.
This can also be used to make one change (In your nav.inc file) and have it reflected across every page including nav.inc.
I hope this helped, and expect some more tutorials soon! (I'm writing these as I go, lol)