PHP Include Files

PHP include Statement

The include statement in PHP is used to include the content of one PHP file into another PHP file. It allows you to reuse code across multiple pages, making your applications more modular and easier to maintain.


The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.



Syntax:


include 'filename.php';




How it Works:

  • When the include statement is executed, PHP will insert the contents of the specified file at the point where the include statement appears in the script.
  • The filename.php can be a relative or absolute path.

PHP include Examples


Assume we have a standard footer file called "index.php", that looks like this:

<?php
include 'header.php';
?>
<h1>Welcome to My Website!</h1>
<?php
include 'footer.php';
?>

Try it yourself

Assume we have a standard footer file called "header.php", that looks like this:

Example
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<header>
<h1>Header Section</h1>
</header>

Assume we have a standard footer file called "footer.php", that looks like this:

Example
<footer>
<p>&copy; 2025 My Website</p>
</footer>
</body>
</html>

In this example:

  • The header.php file is included at the top of index.php to display the header.
  • The footer.php file is included at the bottom of index.php to display the footer.

Differences Between include and require:


  • include: Will generate a warning (E_WARNING) if the file is not found but the script will continue executing.
  • require: Will generate a fatal error (E_COMPILE_ERROR) and stop the script execution if the file is not found.
Example
<?php
echo "Attempting to include a missing file...<br>";
// File does not exist
include 'missing_file.php';
echo "This message will be displayed even if the file is missing.<br>";
?>

Try it yourself

If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error:

Example
<?php
echo "Attempting to require a missing file...<br>";
// File does not exist
require 'missing_file.php';
echo "This message will not be displayed if the file is missing.<br>";
?>

Try it yourself

Note

Use require when the file is required by the application.

Use include when the file is not required and application should continue when file is not found.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.