I have just started using php includes on my website to help me propagate changes across an entire site. So far I have set up include for 3 parts of my site. The header, footer and the navigation, as these are quite likely to change on a regular basis.

I would also like to include the <head> as another section that is mostly recurring across the entire site. The problem is that parts of the <head> will be unique to certain pages. Example:

    <meta charset="utf-8">
    <meta name="description" content="Unique decription for my homepage.">
    <meta name="keywords" content="Some keywords recur, but not all of them.">
    <title>This is unique to the Home page.</title>
    <link rel="icon" type="image/ico" href="/resources/images/favicon.ico"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/main.css"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/nav.css"/>

    <meta charset="utf-8">
    <meta name="description" content="Unique decription for my gallery.">
    <meta name="keywords" content="Some keywords recur, but not all of them.">
    <title>This is unique to the Gallery page.</title>
    <link rel="icon" type="image/ico" href="/resources/images/favicon.ico"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/main.css"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/nav.css"/>

The only way I can think of dealing with this is to include the head and use variables, btw this is pseudocode, I guess you cant just drop variable names in, like this:

    <meta charset="utf-8">
    <meta name="description" content="$homeDescr">
    <meta name="keywords" content="$homeKeyw">
    <title>$homeTitle</title>
    <link rel="icon" type="image/ico" href="/resources/images/favicon.ico"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/main.css"/>
    <link rel="stylesheet" type="text/css" href="/resources/stylesheets/nav.css"/>

I would include the <head> like this (the normal way?):

<?php    $path = $_SERVER['DOCUMENT_ROOT'];
        $path .= "/resources/recurring/head.php";
        include_once($path);    ?>

But I would like to save the variables in a file called variables.php, which would look something like:

$homeDescr="My site offers a super service in the ballpoint pen industry!";
$homeKeyw="ball point ballpoint pen pens super service cheap fast delivery";
$homeTitle="Welcome to Ballpointland! - Home";

$galleryDescr="Look at the great pens we have on offer!";
$galleryKeyw="ball point ballpoint pen pens super pictures photos images gallery";
$galleryTitle="Welcome to Ballpointland! - Gallery";

And so on...

I'm completely newb at php and dont know how including a file that includes variables form another file would work, or even if it would work at all.

I would like it to work in this way because then I could just go to variables.php to update a great deal of meta tags and titles from one place. If it is easier to handle those variable inside head.php then ok.

Please help!

PS. I don't sell ballpoint pens :P

Recommended Answers

All 10 Replies

Yes you can do that, I only suggest you to use arrays:

$data['home']['description'] = 'home descr..';
$data['home']['keywords'] = 'home,descr,..';
$data['home']['title'] = 'Home Title';

$data['gallery']['description'] = 'home descr..';
$data['gallery']['keywords'] = 'home,descr,..';
$data['gallery']['title'] = 'Home Title';

so, for example, if you have parameters in your URL you can use it to get the correct data:

http://www.mysite.tld/index.php?section=gallery

check if section is in $data and display:

include $path;
...
$section = $_GET['section'];
if(in_array($section,$data))
{
    echo $data[$section]['title'];
}
else
{
    echo $data['home']['title'];
}

bye!

commented: genius is wasted! :( +14
Member Avatar for arcticM

just an idea- why not create a class with a static function that gets a set of params and returns an html string with the relevant header info? and then you just call this function and echo that string..

Member Avatar for diafol

//EDIT - sorry saw cereal posted while I was messing about...

I'd use templates for this.

Use a template engine (Smarty/RainTPL/Twig etc). or build your own. Example:

index.php
$title = '...';
$description = '...';

include('templates/head.php');
include('pages/index.php');
include('templates/footer.php');
templates/head.php
...
<meta charset="utf-8">
<title><?php echo $title;?></title>
<meta name="description" content="<?php echo $description;?>">
<link rel="icon" type="image/ico" href="/resources/images/favicon.ico"/>
<link rel="stylesheet" type="text/css" href="/resources/stylesheets/main.css"/>
<link rel="stylesheet" type="text/css" href="/resources/stylesheets/nav.css"/>
...

That sort of thing.

Member Avatar for Zagga

Hi Alochai,

Following on from diafols idea, if you want to keep all the variables in a single file to make it easier to maintain (which I believe is what you are trying to achieve) you could use a single variable to decide which page variables to use.

Change lines 1 and 2 of diafols index.php (and each of your other pages) to:

$thisPage = "home"; // or gallery or whatever the page is called.
include('templates/variables.php');
variables.php
<?php
if (isset($thisPage)){
    if ($thisPage == "home"){
        $description="Home Description";
        $title="Home Title";
    }
    elseif ($thisPage == "gallery"){
        $description="Gallery Description";
        $title="Gallery Title";
    }
    else {
        $error_message = "Page set but not in variable list.";
    }
} else {
    $error_message = "No page set.";
}
?>

For each additional page, you just need to add an additional elseif statement in variables.php and set $thisPage as appropriate.

I really like the combined example of diafol and zagga, but I'd like to ask a question before I implement it. You certainly have done what I asked and supplied me with the ability to use include with variables, but I would like to ask if this is how you would do it? Does it fit with modern web design practices?

Also me and my friend had a discussion about index.php and index.html. He says I should have an index.html in every folder which either includes or redirects in some way to index.php.

The only rational reason I could pin to this is that older browsers might not look for a .php index. All I know is that ive replaced my homepage index.html with index.php and it's working fine.

Finally, I have been including .html files, as they themselves do not have any php written in them, it seems rational to me to believe that appending a file with .php that has no php in it is a waste of time and could possibly cause a browser to do more preprocessing than needed. Is this correct?

I did the same thing that you are trying to acheive by using a function in an includes file that would work out and set a few page variables on page load just as Arctic said.

It's not the browser that looks for either .php or .html, it's the webserver that offers one or the other when a browser is pointed at an incomplete URL - www.mysite.com rather than www.mysite.com/index.html

I agree with your idea about the html includes not needing the php extension and causing the server to needlessl parse the HTML.

Unfortunately what arctic said means nothing to me, I'm not a particularly good programmer.

And as for cereal's post, http://www.mysite.tld/index.php?section=gallery put me off. I could be completely wrong but this seems like it is more useful for heavily scripting one page to serve more than one pages worth of content. For example it would be great at serving translations? E.g. http://www.mysite.tld/index.php?lang=de. I prefer the www.mysite.tld/gallery/index.php server layout.

As with any part of computer sciences there is always more than one way to proceed, some more efficient, some easier and anywhere along those axes. Unfortunatley I have no scope of reference here.

Member Avatar for Zagga

Hi again,

There are certainly ways to improve this idea, it just gives you a basic working model to start with. You could, for example, get the script to check which page it is running on so it can choose the correct page variables automatically.

Whether to implement it really depends on your sites needs. I personally don't use it as my pages each use additional, optional statements in the head section, like JavaScript calls so I would need extra conditional statements to decide what was displayed. I also don't have many pages on my site and decided once I had written the head for a page, it's not going to change that often. If you have lots of pages, or will be changing sections often, looking at a devoted template system (like SMARTY) is probably a better idea, as diafol said.

As adam.adamski.96155 said, it's your server that decides on the default (index) page to show a browser if it isn't explicitly asked for. You can use a .htaccess file to ensure browsers are sent index.php instead of index.html. (there is lots more you can do with .htacces files).

Lastly, again as mentioned above, only save your pages as PHP files if they contain PHP.

Member Avatar for diafol

With regard to cereal's post - it seems to have been dismissed somewhat, but this IS the way to go in order to build a template-based (or even MVC) site. SO I feel the need to expand a little on that.

Most frameworks use index.php file as the only 'page'. Everthing else is ponced off that, e.g.

http://www.example.com/index.php?page=about
http://www.example.com/index.php?page=home

Although it looks weird, it can be made to look really nice with some Apache mod rewriting in .htaccess to this:

http://www.example.com/about/
http://www.example.com/home/

The beauty of this is that the server (due to the .htaccess) still recognises these as the first set of urls, so you can use $_GET['page'] to retrieve the page you need to display.

Many of my own sites, when not using a framework utilise this sort of thing. Example:

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/*$ index.php?page=$1 [L]

Sorry if that's a little off-topic, but once you get the page, you just load the template/include file:

$incfolder = 'includes/';
$tmpfolder = 'templates/';

$page = (!empty($_GET['page']) && file_exists($incfolder . $_GET['page'] . '.php')) ? $_GET['page'] : 'home'; 


include($incfolder . 'config.php'); //contains all the title and desc values for all 'pages'
$title = $config['title'][$page];
$desc = $config['desc'][$page];

include($tmpfolder . 'head.php');
include($incfolder . $page . '.php');
include($tmpfolder . 'footer.php');

That's pretty much it for the index file. It defaults to includes/home.php for the content. If a page exists from the url, that gets included instead (e.g. includes/about.php)

I tend to use .php files for the include files as there are often variable parts to them, sometimes a line of php here or there - although these may be few and far between.

commented: I'm cereal and I approve this message! ;D +9

Well if that is the correct way to do it then I will attempt to implement that way first. My poor confused webserver, it's seen a lot of change recently. sniff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.