PHP Includes

Written by admin on July 7th, 2007 in PHP Tutorials.

PHP has a very handy function called include(). This includes a page within the current page seamlessly. Whereas using iframes or frames in HTML is a seperate page to the parent one. include() can be very useful for when you want to inclide content based on a certain topic. Many CMS programs use the function and so do many many scripts. Here is an example of how include() is used:

<?php

include(‘file.php’);

?> The above code will put all the contents of file.php inside the current parent page. It will inherit all of the variables currently being used by the parent page aswell. So if there are database connections file.php will be able to use them without having to connect again.

Below is an extended version of how include can be used with a security side.

<?php

if(file_exists(‘file.php’)) {

include(‘file.php’);

}

?> That code checks to see whether file.php exists before including all of it’s contents.

If you want to use include() as an easy navigation solution to your website you can use the following function to do it:

<?php

function pageInclude($page) {

if(empty($page)) {

include(‘home.php’);

} else {

if(file_exists($page.‘.php’)) {

include($page.‘.php’);

} else {

echo ‘That page does not exist!’;

}

}

}

?> The above function is very useful for php navigation. To use it your links will be like so: index.php?page=pageone

Then wherever you want your page content to be displayed you will put:

<?php

pageInclude($_GET[‘page’]);

?>

NOTE: Your content pages must be in the same directory as your index.php and must be names the same as what ?page equals without the .php

Hope this helps your understanding of PHP includes. If you need any help please use the comment feature.

Leave a Reply

You must be logged in to post a comment.



Site Navigation