PHP include Keyword

PHP

PHP include Keyword - Include File

Learn how to use the include keyword in PHP to include and evaluate external PHP files dynamically. This tutorial covers the basics of file inclusion, practical examples, best practices, common pitfalls, and optimized ways to reuse code across multiple PHP pages with warning handling on failure.

Introduction

In PHP development, reusing code efficiently is essential for maintainability and modular design. The include keyword allows you to incorporate external PHP scripts or files into your main script. By including files, you can centralize common elements such as headers, footers, functions, or configuration files, reducing code duplication.

Unlike require, include throws a warning if the external file is missing but continues executing the script, making it suitable when the included file is not critical.

Prerequisites

  • Basic knowledge of PHP syntax and script execution
  • A PHP runtime environment (PHP 7 or higher recommended)
  • Access to a web server or local development stack like XAMPP, WAMP, or MAMP
  • Basic understanding of file paths and directory structure

Setup Steps

  1. Ensure PHP is installed and configured on your server or local machine.
  2. Create a project directory structure where you will place your PHP files, for example:
    /project
      /includes
        header.php
      index.php
  3. Write PHP code in your main file (e.g., index.php) to include external files using include.
  4. Test your PHP script in a browser or command line to verify the included file outputs correctly.

Using the PHP include Keyword – Explained Examples

1. Basic Inclusion

Include a simple PHP file named header.php that contains HTML header markup.

<!-- includes/header.php -->
<?php
echo '<h1>Welcome to My Website</h1>';
?>
<!-- index.php -->
<?php
include 'includes/header.php';
?>
<p>This is the main page content.</p>

Output:

Welcome to My Website appears above the main page content.

2. Including with Relative Paths

Be mindful of file paths when including files. Use relative paths based on current script location.

include './includes/header.php';

3. Including Configuration or Functions Files

<?php
// includes/config.php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'password';

// index.php
include 'includes/config.php';
$conn = new mysqli($db_host, $db_user, $db_pass);
if ($conn->connect_error) {
    echo 'Connection failed';
} else {
    echo 'Connected to database';
}
?>

4. Include with Warning on Failure

If the included file is missing, include raises a warning but continues the script execution.

include 'nonexistent.php'; // Warning shown, but script continues

Best Practices

  • Use include when the external file is optional; prefer require for mandatory files.
  • Always use relative or absolute paths carefully to avoid path resolution errors.
  • Organize included files within a dedicated directory (e.g., includes/) for better structure.
  • Keep included files free from side effects; avoid outputting directly except for templating files.
  • Use include_once if the file should be included only a single time to prevent redeclaration errors.

Common Mistakes

  • Incorrect file paths leading to warnings and failure to include the file.
  • Using include for essential files and not handling warnings properly.
  • Redefining functions or variables by including the same file multiple times without include_once.
  • Assuming include stops script execution on failure (it doesn't). Use require if needed.
  • Not validating or sanitizing included content leading to security risks (e.g., including user input directly).

Interview Questions

Junior Level

  • Q: What does the PHP include keyword do?
    A: It inserts and evaluates the contents of an external PHP file into the current script.
  • Q: What happens if the file specified in include does not exist?
    A: A warning is generated, but the script continues execution.
  • Q: How is include different from require?
    A: include gives a warning on failure, require causes a fatal error and stops execution.
  • Q: Can you use relative paths with include?
    A: Yes, relative paths are commonly used to specify the location of included files.
  • Q: What is a practical use of including files with include?
    A: To reuse common UI code like headers or footers across different pages.

Mid Level

  • Q: When should you prefer include_once over include?
    A: To prevent the same file from being included multiple times, avoiding redeclaration errors.
  • Q: How does PHP resolve the path given in an include statement?
    A: PHP searches relative to the current file and according to the include path set in php.ini.
  • Q: How can improper use of include lead to security risks?
    A: Including files based on unvalidated user input can lead to remote file inclusion vulnerabilities.
  • Q: What is the difference between include and include_once at runtime?
    A: include_once checks if the file has been included before and skips inclusion if yes.
  • Q: How do warnings generated by include affect script execution?
    A: Warnings do not stop the execution; the script continues running after the warning.

Senior Level

  • Q: How can the use of include impact application performance, and how to mitigate it?
    A: Excessive includes increase I/O load; caching output buffers or autoloading classes can reduce overhead.
  • Q: How to safely include user-generated file paths using include without security issues?
    A: Validate and sanitize input, restrict allowable paths using a whitelist, and never directly include user input.
  • Q: Explain how PHP’s include path configuration affects the behavior of include.
    A: PHP searches directories in the include_path configuration if a relative path is not resolvable locally.
  • Q: Compare the use of include, require, and autoloading mechanisms for file inclusion.
    A: require halts on failure, include warns but continues; autoloading dynamically loads classes on-demand.
  • Q: How would you debug a silent failure caused by an include in a large PHP application?
    A: Enable error reporting, verify file paths, check include path settings, and log warnings generated by include.

FAQ

Q1. Can I include a non-PHP file using include?

Yes, you can include any file, but if it contains code, PHP will try to execute it. For plain HTML or text, it will be output directly.

Q2. What is the difference between include and include_once?

include_once includes the file just once even if called multiple times, preventing function or class redeclaration errors.

Q3. Does include allow including remote files?

By default, PHP allows including remote files only if allow_url_include is enabled, which is discouraged due to security risks.

Q4. How does PHP handle variable scope in included files?

Included files inherit the variable scope of the line on which they are included. Variables defined in the parent script are accessible in the included file.

Q5. What happens if you include the same file multiple times without include_once?

This can cause function redeclaration errors, class redefinitions, or unexpected behavior due to multiple code executions.

Conclusion

The PHP include keyword is a powerful and flexible way to modularize your code by including external PHP files. It facilitates code reuse, better organization, and maintainability. By understanding how include works, its error handling, and appropriate usage, you can build efficient PHP applications. Remember to handle paths carefully, use include_once when necessary, and always consider security implications when including external files.