Delicious Bookmark this on Delicious

PHP include and PHP require - What for ?


PHP includes allow you to import HTML/PHP code from external files to your current PHP script.

This allows you to reuse the same lines of code with only one declaration and might be very useful, for instance when you want to assign the same template to all the pages of your website without including the whole code of this template within every webpage.

Thefore, if you need to modify the template of your webpages in the future, all you will have to do is modify the original template file and all the other pages of your website will automatically be updated since they all fetch their code from this file. The PHP syntax of the include() statement will be introduced below.



Computer Forums

PHP include and PHP require - PHP include


Given a file whose path is called file_path (file_path is a string giving the address of the file, for instance 'file.php' or '/folder/file.php', etc ...), the PHP syntax is given by:
include(file_path)

In the example below, a file called complements.php will be added as an include within another file called main.php (in order to simplify the path, we will put both files in the same folder).


Learn the PHP code:

complements.php
<?php
$s = 1;
?>

main.php
<?php
include('complements.php');
echo $s+1;
?>



Run the PHP script in your web browser:

php include() statement


Remark:

When executing an include() statement, the external file which has been included is processed as HTML by default, even though the include statement was inserted within a php script.
If the include file contains PHP code, you must place that code between the tags <?php and ?> within the include file itself.


Computer Forums

PHP include and PHP require - PHP require


The only difference between the PHP include and PHP require statements is that the PHP require() statement triggers a fatal error when the file included cannot be found, while the include() statement only issues a warning.


The PHP include() and require() statements() allow you to reuse your PHP code and gain time and flexibility. Typically, they allow you to group variables or functions in one PHP file and then make them available to any other page of your website. They also allow you to optimize the development of templates for more flexibility.


Computer Forums

Next tutorial: PHP functions
Previous tutorial: PHP array and array of arrays

Back to computer forums