Including files with php is very easy to do. This tutorial shows you how.
The main reasons why you might use php includes/require one of these reasons is to include the footer in to every page but only have one footer.
Let me explain you create a new file in can be a .html or .php extension either will work I always choose .php extension as I usually has some php running even in the footer.
In your new file save it as footer.php and in the file only have what you want in the footer do not put in the doc type or <html><title>..ect as you will already have this information in your other pages that this footer will be included with.
this is an example of a footer file:
<div id="footer">Copyright © your name <?php echo date('Y');?> </div><!-- close footer -->
This is the full footer.php page. When its included into another page and you look at the source code it looks like its all one page.
Okay so now you can see why including a file is useful. But before going into how to include a file you need to decide if you want to use includes or requires.
Include VS Require
When including/requiring a file as long as the file is found there is no difference in these two methods. But if the file cannot be found they act very differently.
Includes will show you an error if the file is not found and will continue loading the rest of the page, But if your using require and the file is not found you will see an error message and nothing else below where the error message occurs.
The reason for this is if a require cannot find the file it is looking for it stops the rest of the page/script from loading.
So if your page needs to connect to a database and your want all pages to link to the database connection page then use require. In most cases you can use includes. Its your preference which method you use.
How to includes a file with includes or require
To include a file you would write the following code:
<?php include ('footer.php'); ?>
//or if your included file is in another folder:
<?php include ('folder-name/footer.php'); ?>
First we open php with <?php the use the function include () between the parenthesis is where the file is located, So if the file is in the same folder as the page using the include you would use (‘filename.php’) then remember the semicolon on the end ‘;’ then close php with ‘?>’
Using require is almost the same:
<?php require ('footer.php'); ?>
//or if your required file is in another folder:
<?php require ('folder-name/footer.php'); ?>
The only difference in the code is instead of using include were using require.