File Inclusion in PHP Language
File inclusion is a powerful feature in PHP that allows you to include the content of one
File inclusion is a powerful feature in PHP that allows you to include the content of one
include
and require
, along with examples.
include
Statement in PHP LanguageThe include
statement is used to include a file within another PHP script. If the included file is not found, it will generate a warning but will not halt script execution.
Example:
Suppose you have a file named “header.php” containing the HTML header for your web page:
<!-- header.php -->
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
You can include this header in another PHP file using include
:
<!-- index.php -->
<?php
include('header.php');
?>
<!-- Rest of your web page content -->
This will include the content of “header.php” in “index.php.”
require
Statement in PHP LanguageThe require
statement is similar to include
in that it includes a file within another PHP script. However, if the included file is not found, it will generate a fatal error and halt script execution.
Example:
Continuing with the “header.php” example:
<!-- header.php -->
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
You can use require
to include this header in another PHP file:
<!-- index.php -->
<?php
require('header.php');
?>
<!-- Rest of your web page content -->
This works the same way as include
, but it’s more stringent. If “header.php” is missing, it will cause a fatal error.
include_once
and require_once
Statements in PHP LanguageTo prevent a file from being included multiple times, PHP provides include_once
and require_once
statements. These statements ensure that a file is included only once, even if you attempt to include it multiple times within your script.
Example:
<!-- index.php -->
<?php
include_once('header.php');
include_once('header.php'); // This will not include 'header.php' again.
?>
<!-- Rest of your web page content -->
These statements are useful when dealing with complex applications to avoid issues related to variable redefinition or function redeclaration.
Subscribe to get the latest posts sent to your email.