In this tutorial I will present two important functions that PHP has: include and require.
‘Include‘ is used for “importing” another PHP page into the one where is called. So it takes all the code from the invoked page using it in ours. This PHP page will run even if the page called in include is not present.
In comparison ‘require‘ does almost the same thing, but PHP page will return an error if it’s not found.
Using this two functions we can split and organize our code, so they are very useful. But it’s recommended to use this only when needed, so don’t abuse them. I will show some small PHP code on how to use them.
Include :
Let’s assume that we have the following code :
HTML:
<a href="/index.php">Home</a>
<a href="/links.php">Links</a>
<a href="/about.php">About</a>
We put the code above in menu.php, for example.
Then using it in our index.php or in another page becomes very simple just:
<?php include("menu.php"); ?>
It’s very easy.
Require:
Let’s make a page called require.php:
<?php
echo "Require test";
?>
After that we make another page called tutorial.php for example.
<?php
require("require.php");
echo "
";
echo "Test succesful";
?>
If we run tutorial.php in browser we will see:
Require test
Test successful
But if require.php cannot be found we will have an error and the script will stop to execute:
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.
In the future I will go with more advanced tutorial, but bare with me as these are dedicated to those people who are trying first time PHP coding.
Leave a Reply