Explain include(),require(),include_once() and require_once() functions in PHP.

In PHP, file inclusion functions allow you to incorporate external PHP files into your current script. The four main functions − include(), require(), include_once(), and require_once() − serve similar purposes but differ in their error handling and inclusion behavior.

include()

The include() function includes a specified file. If the file is not found, it generates a warning but continues script execution ?

<?php
    // main.php
    echo "Before include<br>";
    include 'header.php';  // File exists
    echo "After include<br>";
    include 'missing.php'; // File doesn't exist - warning only
    echo "Script continues<br>";
?>

require()

The require() function includes a file but generates a fatal error if the file is missing, stopping script execution immediately ?

<?php
    // main.php
    echo "Before require<br>";
    require 'config.php';  // File exists
    echo "After require<br>";
    require 'missing.php'; // File doesn't exist - fatal error
    echo "This won't execute<br>"; // Won't reach here
?>

include_once()

The include_once() function includes a file only once. If the file has already been included, it won't include it again ?

<?php
    // functions.php contains: function greet() { echo "Hello!"; }
    
    include_once 'functions.php';  // First inclusion
    include_once 'functions.php';  // Ignored - already included
    
    greet(); // Works fine, no "function already declared" error
?>

require_once()

The require_once() function combines the behavior of require() and the "once" feature. It includes a file only once and generates a fatal error if missing ?

<?php
    require_once 'database.php'; // Essential file - must exist
    require_once 'database.php'; // Won't include again
    
    // Continue with database operations...
?>

Comparison

Function Error on Missing File Continues Execution Prevents Re-inclusion
include() Warning Yes No
require() Fatal Error No No
include_once() Warning Yes Yes
require_once() Fatal Error No Yes

Best Practices

Use require_once() for essential files like configuration or database connections. Use include_once() for optional components like headers or footers that shouldn't break the page if missing.

Conclusion

Choose require() or require_once() for critical files that your script cannot function without. Use include() or include_once() for optional files where the script should continue even if the file is missing.

Updated on: 2026-03-15T08:11:17+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements