PHP Include
PHP Include & PHP Include_once
The “include” php statement is used to include other files into a PHP file.
It has two variations, include and include_once. Include_once is ignored by the PHP interpreter if the file to be included. Include/include_once” is the statement that includes file. “'file_name'” is the name of the file to be included.
Suppose you are developing a website that contains the same navigation menu across all the pages. You can create a common header then include it in every page using the include statement Let’s see how this can be done.
<?php
include 'header.php';
?>
PHP Require & PHP require_once
The require statement has two variations, require and require_once. The require/require_once statement is used to include file. Require_once is ignored if the required file has already been added by any of the four include statements.
<?php
require 'file_name';
?<
<?php
require_once 'file_name';
?<
PHP Float
Suppose we are developing a database powered application. We can create a configuration file that we can include in all pages that connect to the database using the require statement. config.php
Variable with global scope:
<?php
$config['host'] = 'localhost';
$config['db'] = 'my_database';
$config['uid'] = 'root';
$config['password'] = '';
?>
<?php
require 'config.php'; //require the config file
//other code for connecting to the database
?>
Php include vs require
The difference between include / require
Jnclude | Require |
---|---|
Issues a warning when an error occurs | Does not issue a warning |
Execution of the script continues when an error occurs | Execution of the script stops when an error occurs. |
Generally, it’s recommended using the include statement so that when an error occurs, execution of the script continues to display the webmaster email address or the contact us page.
The require statement should be used if the entire script cannot run without the requested file. The “include” and “require” statements can be used at any line in the source codes where you want the code to appear.