Help - Search - Members - Calendar
Full Version: Php Include Explained
Zymic Webmaster Forums > Zymic Free Web Hosting > Tutorials
IamShipon1988
Title: php Includes
Language: php, XHTML, CSS
Skill Level: Basic
Author: Sazzad Hossain
Demo: http://www.amuz.us

Authors Note: PHP is perhaps one of the simplest language you can earn that can grant you much freedom with your site. In addition, it can also make your life a lot easier. If you are a web-designer you will see why. First of all, php has many functions that allow you to substitute for a long list of codes. For example, in this tutorial I will talk about php include. What php include basically does is takes an entire page of coding from one location and brings it to the page where you requested it. So if I have a head section located in "/include/head.php" and I want it to show up in my index.php file; all I have to do is call for it using php include.

So whats an advantage of include?
If you want to modify your site, and you have tons of page, and do not want to modify each one of them separately; when you use php include, all you have to modify is the file your including. In this example, all you have to do is modify the header.php and footer.php (also the style.css) that will change the layout to whatever you wish. It sort of acts as an StyleChanger effect but it requires a bit more work.

Step 1: Create the file you want to call for. Example, this header file: "includes/header.php." So we have these codes for the header file:
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
    <title>

    </title>
    <link rel="stylesheet" type="text/css" href="includes/style.css" />
</head>
<body>
<div id="holder">
<!-- holds the title and the navagation bar -->
<div class="header">

    <!-- holds the logo -->
    <div id="logo">
        <img src="../images/logo.idontknow" alt="RIT Web Dev Logo" />
    
    </div>

    <div id="nav">
    <br />
        <a href="index.php" alt="home">Home</a>|
        <a href="forum.php" alt="forum">Forum</a>|
        <a href="members.php" alt="members">Members</a>|
        <a href="about.php" alt="about">About</a>|
        <a href="contact.php" alt="contact">Contact</a>
    </div>
    <hr />
    </div>

Step 2: Since we will not have the ability to edit this page for the pages that will have a different title, we will need to add a variable that will allow us to accomplish that. So in order for us to give custom title to our main pages, we will need to replace the title tags with the following:
CODE
<title>
<?php
    echo $title;
?>
</title>

Step 3: Now lets create our footer file (you can create a sidebar, but I'm skipping that for the sake of time). We don't have to make any changes in this file unless you want to include something else from another location. Lets call this file footer.php and put it also in the includes folder.
CODE
    <hr />
    <div class="copyright">
        © 2007 RIT Web Developers, All Rights Reserved <br />
            <a href="contact.php"> Contact Us </a>
    </div>
</div>
</body>
</html>

Step 4: Okay, since we are now done with all the files we want to include in our index.php file, lets create the most important file: index.php. A general HTML file without header and footer will look something like this:
CODE
<div id="content">
    <h1> Content Title </h1>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce quis ante.
    Ut sit amet arcu eu lacus sodales egestas. Sed metus risus, placerat vitae,
    molestie sit amet, consequat eu, erat. Quisque tincidunt, urna sed
    pellentesque adipiscing, risus nulla congue urna, et pharetra tortor massa
    in leo. Cum sociis natoque penatibus et magnis dis parturient montes,
    nascetur ridiculus mus. Quisque tellus. Phasellus iaculis lacinia diam. In
    nonummy, tortor id rutrum fermentum, metus lacus ultrices turpis, sit amet
    hendrerit pede leo vitae neque. Aenean lacinia metus eu tellus. Quisque
    tempor dolor at velit. Etiam luctus fermentum justo. Pellentesque erat
    mauris, consectetuer a, commodo at, ultrices vel, lacus. Proin sit amet
    leo. Vivamus sit amet tellus.
    </p>
</div>

But that does not include our header.php and footer.php. So we need to call for it. We can accomplish this by using 3 lines of php codes. So above all the codes in our index.php code, we want to include our header. We can do this by pasting the following code:
CODE
<?php
    include("includes/header.php");
?>

Step 5: Remember when we added echo $tittle; in our header to allow us to give the page custom title? Well this is the additional work needed to accomplish that. Before the area where it states include("includes/header.php"); we will add the following line of title:
CODE
    $title = "Page 1";

Simply replace the Page 1 with your own page title.
Step 6: Now its time for us to call our footer. This can be accomplished the same way as in step 4. Simple paste the following code towards the bottom of the index.php file.
CODE
<?php
    include("includes/footer.php");
?>


Well your done! What you have to note is that you can place footer.php and header.php in any folder you want, just make sure you call it correctly. Many php programmers make that mistake, thereby end up spending hours finding the problem, although the problem is simple. Just as a word of warning/caution Windows versions of PHP prior to PHP 4.3.0 do not support accessing remote files via this function.

If you put all these codes together, you should get a page similar to the demo page (unless I end up modifying the page). If you want to use the same css, then here it is:
CODE
.copyright {
}
.header {
    border: thick #000000;
    text-align:center;
}
#holder {
    margin: auto;
    width: 700px;
}
#logo {
}
#main {
}
#nav {
}
/***************
    Links
***************/
a:hover {
    text-decoration:underline;
}
a {
    text-decoration:none;
    color:#0066CC;
}


Cool Extras:
- PHP Date & Time function
Ed
Thanks for taking the time to write this IamShipon1988, I'm sure someone will find enlightenment in it smile.gif.

Little bit of constructive criticism, first one is because I'm pedantic; includes, requires etc should really not include the parenthesis as they're language constructs as opposed to functions. Doesn't hinder it at all, it's just better to write them without the suggestion they're functions.

Second one is just to include possibly an overall finished article with the head, body and footer.

Other than those minor bits, nice job.
MrTouz
basically include = iframes

its installing an exterior content to the page but differently then the iframe the code you include is directly added to the rest of the code like a puzzle smile.gif.

example :

i include my header which is ( <table><tr> )

than i have my content which is (<td> /<td> )

i include my footer which is ( </tr></table>)

which is kind of like a puzzle it takes part of codes from different places to make a big one !
IamShipon1988
Bread
Thank you for your comment. Yes it is true that you do not need the parenthesis, however, it does help a bit with the organization. I know when coding in Java or C, I used to delete certain characters when using the get function because I didn't know where the file location name started. So to prevent that form happening in PHP, like to use the parenthesis. But its really solely up to the user.

MrTrouz
Yes it is true that it is "sort of like a iframe" however it is very different. Here's something that I once read a while ago that helped explain things for me.

iFrames can display another website's information, something include's can't. If you are passing information from the include, you can only do that with an include, not an iframe. iFrames load a page onto a certain file, includes do not. It rather gathers the source code from a file and imports it to whichever other file has called for it. One thing that people say is includes make your website load slow. Yes, an include has to be loaded on each page, but it gets cached and loads extremely fast after a while.

If you would like more information here is the book for the include function that the creators of PHP had created: http://us.php.net/include/

Please do note that the include function (if you observe carefully) is used in many of the scripts created (php based). It can be listed on the index.php file as
CODE
includes="config.php"
MrTouz
CODE
Yes, an include has to be loaded on each page, but it gets cached and loads extremely fast after a while.


the CACHE ... that is why my site loads a lot faster, before i had to wait till it showed not the content.. mostly the images just load at once.

well i have to wait the first time i ever get on the page... but the second time.. it just pops it up smile.gif

i started using includes a week ago, and im sure im about to use it for a really long time.
IamShipon1988
Well I'm really glad to hear that. Includes is a great function that many php coders love to use.
Paranoid
Includes let me update my new layout/update large sections of my site without having to change every single web page of mine.
This feature is really nice...
eJGDesigns
QUOTE
the CACHE ... that is why my site loads a lot faster, before i had to wait till it showed not the content.. mostly the images just load at once.


How do i do this what you have done?

Thanks
IamShipon1988
eJGDesigns, php includes does this automatically after the first visit. Its a built in function that is recorded into your browser. Just use includes and the chche work will take care of itself.
doughnut
I Love PHP includes="file.xxx"

lol smile.gif
IamShipon1988
QUOTE(doughnut @ Dec 15 2007, 02:44 AM) *
I Love PHP includes="file.xxx"

Me tooo!!! Before in c, you had to do a lot of extra coding to get what that 1 statement does...its soo awesome!
Eibwen
You also can do require_once "file.xxx"; or require "file.xxx"; smile.gif
IamShipon1988
Well yes you can use require_once, but sometimes people want to use the function more than once. People normally use require_once for stuff like config.php files where they want to require people to login to the account.
doughnut
QUOTE(IamShipon1988 @ Dec 15 2007, 06:28 AM) *
Me tooo!!! Before in c, you had to do a lot of extra coding to get what that 1 statement does...its soo awesome!


ya i love that one to some times!!!! .... LOL laugh.gif

i use php...
CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<title>{ Noise Bomb }</title>
</head>
<body>
<div id="container"><?php require_once "settings.php"; settings ?>
    <h1 class="logo"><a href="/" title="{ Noise Bomb } v1.0"></a></h1>
    <h1 class="inserts"><?php require_once "sources/inserts.php"; inserts ?></h1>
    <ul id="navigation">
    <?php include "navigation.php"; navigation ?>
    </ul>
<div id="menu" class="menu-content">
    <h2>Menu</h2>
    <ul>
    <?php include "menu.php"; menu ?>
    </ul>
<div class="box">
    <?php require_once "promote_us.php"; promote_us ?>
</div>
</div>

<div id="footer">
    <?php include "footer.php"; Footer ?>
</div>
</div>
</body>
</html>


Cant giv out all my site info lol smile.gif
Nexus
This is a nice tutorial. I found about the php include and require/requie_once scripts by trial and error myself lol. That's the only bit of PHP I know at the moment.
doughnut
QUOTE(Nexus @ Dec 23 2007, 03:00 PM) *
This is a nice tutorial. I found about the php include and require/requie_once scripts by trial and error myself lol. That's the only bit of PHP I know at the moment.


Ya im new to php to but i look at how forums and scripts are med and i add to Or remake it to how i like it +i look up and try to help any one i can
like on my forum noisebomb community its now so plz feel free to come and post all you like.
O and i need some admin
IamShipon1988
Nice advertisement doughnut. Don't worry I wont say anything lol. I'm doing the same in my sig. I took a look at your forum and I have to say, I am not a big fan of MyBB. Although myBB was designed to look and function as a free version of IPB, it's not doing a good job in my opinion.

I often do trial and error. Often people send me messages online asking for help on scripts I have never heard of before. I just stare at the code for some time and I see the pattern. That way I can see what each line of code does. I think that is the best way to mod. lol.
doughnut
QUOTE(IamShipon1988 @ Dec 24 2007, 07:09 AM) *
Nice advertisement doughnut. Don't worry I wont say anything lol. I'm doing the same in my sig. I took a look at your forum and I have to say, I am not a big fan of MyBB. Although myBB was designed to look and function as a free version of IPB, it's not doing a good job in my opinion.

I often do trial and error. Often people send me messages online asking for help on scripts I have never heard of before. I just stare at the code for some time and I see the pattern. That way I can see what each line of code does. I think that is the best way to mod. lol.


Ya im starting to not like mybb im going to go back to "punbb" or "phpbb3", whqat you tank? "IamShipon1988" hey y did you not Register at my forum?

mellow.gif
Is all the link's "Personal | Hip Hop Clique | MicroDiary | Mint Tools | Fleech Media, Inc." your sites?
IamShipon1988
Yes they are. I'm in the process of renovating some of them. I own Fleech Media, Inc. and that company owns many sites and its all hectic right now. We started decorating all sites for christmas and I got a headache right now.

I did not register for the site because you are using myBB. LOL. Sorry I just don't like that board. It's very simple to hack/get a hold of the config file.
doughnut
QUOTE(IamShipon1988 @ Dec 24 2007, 11:14 PM) *
I did not register for the site because you are using myBB. LOL. Sorry I just don't like that board. It's very simple to hack/get a hold of the config file.


Wow ty i did not know that i del "mybb" and put up "phpBB3" so if you know how to work it plz help me out i do not get how to make a new forum/Category.

Ok hold on update i got a new "Category" but i can only see it win i am not login WTF?

Note: If you register "IamShipon1988" ill make you a admin so you can show me how to work it. if you cant you can be a admin to i like you lol smile.gif
IamShipon1988
Registered on your forum. I'm going on vacation so I wont be around much for the next week or so.
doughnut
QUOTE(IamShipon1988 @ Dec 25 2007, 10:20 PM) *
Registered on your forum. I'm going on vacation so I wont be around much for the next week or so.

that sucks But have FUN smile.gif you are a admin on my forum i tank!
IamShipon1988
Haha I forgot I registered on your forum, anyhow this topic is going off-topic lol. Add me on messenger or PM me if you wanna chat or have questions.
smartalco
I'm not particularly new to php, however, until the last couple of days I haven't done anything in the last 5 months or so, and I am having problem with includes

i have used both "include 'includes/template.php';" and "include ('includes/template.php');" and both generate the error ->

"Parse error: syntax error, unexpected T_INCLUDE in /www/zymichost.com/d/e/s/destinationhays/htdocs/index.php on line 4"

I have dealt with this problem before, it has just been so long I don't remember how

any help?
Alex
We need to see the whole file, likely the syntax error is before that line.
smartalco
ya... just figured it out, left out a semicolon on the previous line, took me an hour to figure this out :/
IamShipon1988
Hehe...good work on solving it. This is something I learned while learning coding in IC, C and JAVA; always look 3 lines before and after the reported error line. It really helps in my opinion.
Vanumi
Hello!
I'm new here in ZYMIC.

I wanted ask you a question, maybe somebody can help. I'm developing my first serious web page. I use PHP and I decided to use "include" in the moment I saw that the code is enormous and I couldn't navigate through it. It worked very fine while it was on my laptop. But in the moment I transfered all into ZYMIC (I needed ability to work without my laptop) it stopped working.

The code is:

CODE
<?php
include ("/Something.php");
?>


I can't find a problem.

For now rest of the code in main page are HTML. And if I write

CODE
<?php
echo "Hello!";
?>


it works fine, so I think mistake must be in "include" itself. Maybe path? But the file I need is in the same directory as the file from where I call it.

Can anybody help, please?
Alex
If it's in the same directory you don't include a /, because that means "root" (be it the actual root or the document root), for "this dir" you can do either of the below:

CODE
<?php
include 'file.php';
// OR
include './file.php';
?>


"./" means "this dir", and if you want to go down one directory that's "../".
Vanumi
Thanks, Alex! include 'file.php' didn't work, it was my very first try, but include'./file.php' did work. It is very interesting that I didn't find this small fact in any tutorial or example I read before.
Now another problem popped up, but I'll try to sort it out myself first. I have few guesses what could be wrong. But if I won't manage to do it, I'll ask for your help again. Thank you. rolleyes.gif
IamShipon1988
It's a bit awkward that 'file.php' didn't work. Normally I use './file.php'/ for smarties related sites.
omerts
Thank you for the information it was very helpful
IamShipon1988
QUOTE(omerts @ Mar 4 2008, 10:15 AM) *
Thank you for the information it was very helpful

You're always welcome.
Alex
QUOTE(IamShipon1988 @ Dec 15 2007, 07:28 AM) *
Me tooo!!! Before in c, you had to do a lot of extra coding to get what that 1 statement does...its soo awesome!


I'm late to this thread, but... wink.gif

I kinda feel like pointing out there is an #include included in ISO C that does a more primitive version of what PHP's include does.

Also PHP's include isn't really best described as "taking the contents of a page and then acting as if they were in the including file", because you can write some quite trivial examples where this turns out to not be the case. The implication there is that the code is taken verbatim and then executed (like an eval(file_get_contents(...)) would do), but if you nest includes together you'll notice that if /fileA.php includes 'a/fileB.php' and that file has "include 'b/fileC.php' then that include will not include /b/fileC.php but rather /a/b/fileC.php, the relative path is preserved. That kind of thing makes me dubious about describing it in those terms.
IamShipon1988
In the later version of C #include is usable. However, in the older version, this was not an option.

You are right about the include. I should have written that in the intro, but I forgot. I'll include that soon. I need to get some sleep for today.
machiko99
complete and clear...thank you boss
noetfd
I need to recode my site after reading this haha, I've used php includes before in like 2004 but it wasn't clear to me after 6 years away, this thread brought me back to speed thanks
shans2213
Nice shared.. Thanks.
IamShipon1988
I'm happy to see that this tutorial has helped you all. If you would like to learn about another php function, then let me know. I will try my best to write a tutorial on that in the same manner as this.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2013 Invision Power Services, Inc.