The vast majority of dynamic websites or applications need to reuse parts of identical code in several places of the same page, or in several different pages. This is the case for example libraries of user functions or configuration files. Rather than rewrite each time the code, there are functions (actually language constructs) that can import and execute the code reuse in the page. These are the include () and require ().
We’ll be covering the following topics in this tutorial:
The include () and require ()
Firstly why there are two different functions that perform the same function? Their operation is exactly the same but the difference between them lies in the error handling.
Include () will return an error of type WARNING if it does not open the file in question. Thereby running the code in the following page will be executed. However, the require () function will display an error FATAL type that stops the execution of the script.
Which prefer then? Everything depends on context. If the file must be present for the rest of the program, then require () is preferred if an include () will do.
How to use include () and require ()
These two functions take a single parameter type string. This is the path to the file to import. The path is relative default relative to the directory that contains the script. Illustrate this with examples:
<? php
// Imports with require ()
require ('../ folder/file.php');
require 'file2.php';
// Imports with include ()
include ('../folder /file.php');
include 'file2.php';
?>
We note here two possible syntaxes for each. Parentheses are optional (as echo () for example).
Explanation: In the first import of each function, we ask to include the file “file.php” found in the “Folder” at the same level as the script “../”. ../ We go through the levels file tree (return to the parent folder). In the second import, we want to import the file “file2.php” found the same level as this script.
When a file is imported, the code found inside runs. The variables, constants, objects, paintings … the imported file can be reused later in the program. Let’s take a simple example. We have a “config.php” file containing the following code:
File Listing "config.php"
<?php
// Define the variables
$a = 15;
$b = 5;
// Display a text
echo 'A little math ...<br />';
?>
Then a main program named “program.php” contained the same level as the first, which contains the following lines:
File Listing "program.php"
<?php
// Import and execution file
require ('config.php');
// Calculate the sum
$sum = $a + $b;
// Display the sum
echo 'Sum of $a + $b = ', $sum;
?>
The result of the execution of the code is as follows:
Result of the execution of the file "programme.php"
A little math ...
Sum of $a + $b = 20
The sum of $a and $b are displayed on the standard output. We conclude that the variables have been created to import the file and then used in the main program.
Note: these functions are used only for pages with PHP code to execute. To import pure static pages (html or text, for example), use file_get_contents () preceded by an echo () statement.
Require_once () and include_once (), what is it?
The functions require_once () and require_once () allow you to import only once a file if there’s several attempts to import the file into the page.
However the use of these two functions is impaired for optimization purposes. They are indeed slower than their respective little sister because they must also check that the file has been imported once.
Include () and require (), susceptible to hacking !!!
There is a very dangerous security flaw when these functions are not used correctly. This is a flaw related to neglect and ignorance of novice programmers.
In our previous examples, there was no risk of piracy because we had entered file paths hard. But what happens if we write a horror like this?
Dynamic import of example of unsecured page
<?php
include ($_GET ['page']);
?>
Remember the tutorial on forms processing. $_GET Array contains all values ? passed in the url. In this example, we put a variable named page in the url that contains a value. Three scenarios of behavior include () available to us:
• The value of $_GET [‘page’] is empty or bad therefore include () can not be imported and an error.
• The value of $_GET [‘page’] is filled and is an existing file server. The import will be no problem.
• The value of $_GET [‘page’] is filled but contains the address leading to a dangerous present on a different server pirate file. For example $_GET [‘page’] is http://www.domain.com/hack.php. The file will be imported hack.php and hacked site !!!
We will have understood, it MUST NOT use the code above to dynamically import files.
What solutions can we put in place in this case? The first is first prefix and suffix of the variable to make false links to pirated files and prevent their importation. This example gives:
<? php
require ('/ path/to/something /' $_GET ['page'] '/ php'...);
This code protects us from malicious imports but does not put us in the shelter of an unsightly error on the screen if the file does not exist and may not be imported. An interesting solution is to use an associative array whose key matches the value passed in the variable $ url of the page, and the value the file name to import.
If the code is written in the index.php file, then the pages will be Called well:
• http://www.domain.com/index.php?page=tutorials
• http://www.domain.com/index.php?page=downloads
• http://www.domain.com/index.php?page=contacts
Note: the pages are located in a directory called “pages” on the same level as “index.php”
Dynamic import of such secure pages
<?php
// Array of files to import
$arrayPages = array (
'home' => 'homepage.php',
'tutorials' => 'tutorials.php',
'downloads' => 'downloads.php',
'contacts' => 'contacts.php'
);
// Variable $page-it exists in the url?
if (!empty ($_GET ['page']))
{
// Check the value passed in the url: is it a key of the table?
if (array_key_exists (strtolower ($_GET ['page']), $arrayPages))
{
// Yes, so it is important
include ('pages/' . $arrayPages [strtolower ($_GET ['page'])]);
}
else
{
// No, so we import a default file
include ('pages/error 404.php');
}
}
else
{
// No, it displays the default home page
include ('pages/' . $arrayPages ['home']);
}
?>
In this example, we check that the page in the URL corresponds to an array key (see: array_key_exists() function). If so, then it is important, if not a 404 page are included (file not found). Note the presence of the strtolower () function that forces the value of $_GET [‘page’] in lowercase.