PHP Include Files

📂 PHP Include Files Tutorial

PHP allows you to reuse code across multiple pages using include and require statements. This is useful for header, footer, menu, or configuration files.


1️⃣ include Statement

include inserts the content of one PHP file into another.
If the file does not exist, PHP shows a warning but continues execution.

Example: header.php


 

Example: index.php


 

Output:


 


2️⃣ require Statement

require is similar to include, but if the file does not exist, it throws a fatal error and stops execution.


 

✅ Use require for essential files, e.g., configuration or database connection.


3️⃣ include_once and require_once

  • include_once – Includes the file only once, even if called multiple times.

  • require_once – Requires the file only once, prevents duplicate inclusion.


 


4️⃣ Example: Including Header and Footer

header.php


 

footer.php


 

index.php


Output:


 


5️⃣ Advantages of Include Files

  1. Code Reusability: Write once, use anywhere.

  2. Ease of Maintenance: Update one file, all pages reflect changes.

  3. Organization: Separate logic, header, footer, menus, and configuration.

  4. Prevent Redundancy: include_once / require_once avoid multiple inclusions.


🏁 Summary

  • Use include for optional files, require for essential files.

  • *_once variants prevent duplicate inclusion.

  • Useful for headers, footers, menus, database connections, and reusable functions.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *