CGX Blog We'll see where this takes us.

13Oct/100

PHP Hooks

When creating a website using PHP it's typically most logical to implement templates, as described in an earlier post.  If you implement templates then you're page structure is always:

< ?php include ("/templates/header.php") ? >
<!-- Changeable content -->
< ?php include ("/templates/footer.php") ? >

This is perfect for most pages.  However, what if you have a particular page, or set of pages, that requires custom header information?  For example, a page that requires a unique javascript file or CSS file.  Enter PHP Hooks.

The principle is simple, you enter a snippet of code into your header.php that will look for a HOOK from the page calling header.php.  If that HOOK is found, it inserts it into the header.php file!  Let's look at a simple example - a page called fun_script.php requires a javascript file and custom css file that we don't want to have loaded on every page of our website.  We would simply need the following:

HEADER.PHP

<html>
 
<head>
 
<title>Page Title</title>
 
<link rel="shortcut icon" type="image/x-icon" href="/images/favicon.ico" />
<link rel="stylesheet" type="text/css" href="/css/core.css" />
 
<?php 
    /*Insert data intended for bottom of header (i.e. to override core.css)*/
    if (isset($header_bottom_hook))
       { echo $header_bottom_hook; }
?>
 
</head>

FUN_SCRIPT.PHP

<?php
//Define root directory:
$root = $_SERVER['DOCUMENT_ROOT'];
 
//Define Hook for page specific header information
$header_bottom_hook = '
<link href="css/custom_style.css" rel="stylesheet" type="text/css" media="all" />
<script type="text/javascript" src="lib/custom_js.js"></script>
';
 
//Include the header file
include ("$root/templates/header.php");
 
?>

Conclusion

That's all there is to it.  Now you are able to selectively insert stylesheets or javascript files into your header.  If it turns out you want a space for stylesheets that won't override your core.css file then you can add a "header_top_hook" above your standard stylesheets :)

Filed under: PHP Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


*

No trackbacks yet.