Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP is included


May 11, 2021 PHP


Table of contents


PHP contains files


PHP include and require statements

In PHP, you can insert the contents of a PHP file in the file before the server executes it.

The include and require statements are used to insert useful code written in other files into the execution stream.

Include and require are the same in every other way except in different ways:

  • Require generates a fatal error (E_COMPILE_ERROR) after the error occurs and the script stops executing.

  • include generates a warning (E_WARNING) that the script continues to execute after the error occurs.

Therefore, if you want to continue and output the results to the user, use include even if the containing file is missing. O therwise, in framework, CMS, or complex PHP application programming, always use require to reference critical files to the execution stream. This helps improve the security and integrity of your application in the event of accidental loss of a critical file.

Containing files saves a lot of work. T his means that you can create standard headers, footers, or menu files for all pages. Then, when the header needs to be updated, you simply update the header to include the file.

Grammar

include ' filename ';
or
require ' filename ';

Tip: For include, the file is read and evaluated every time it is executed, and for require, the file is processed only once.


PHP include and require statements

The underlying instance

Suppose you have a standard header file named "header .php." To reference this header file on a page, use include/require:

<html>
 <body>

 <?php include 'header.php'; ?>
 <h1>Welcome to my home page!</h1>
 <p>Some text.</p>

 </body>
 </html>

Instance 2

Let's say we have a standard menu file that is used on all pages.

"menu.php":

echo '<a href="/default.php">Home</a>
 <a href="/tutorials.php">Tutorials</a>
 <a href="/references.php">References</a>
 <a href="/examples.php">Examples</a> 
 <a href="/about.php">About Us</a> 
 <a href="/contact.php">Contact Us</a>';

All pages in the site should reference the menu file. Here's how:

<html>
 <body>

 <div class="leftmenu">
 <?php include 'menu.php'; ?>
 </div>

 <h1>Welcome to my home page.</h1>
 <p>Some text.</p>

 </body>
 </html>

Instance 3

Suppose we have an inclusion file that defines a variable ("vars.php"):

<?php
 $color='red';
 $car='BMW';
 ?>

These variables can be used in the call file:

<html>
 <body>

 <h1>Welcome to my home page.</h1>
 <?php include 'vars.php';
 echo "I have a $color $car"; // I have a red BMW
 ?>

 </body>
 </html>