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
-
Code Reusability: Write once, use anywhere.
-
Ease of Maintenance: Update one file, all pages reflect changes.
-
Organization: Separate logic, header, footer, menus, and configuration.
-
Prevent Redundancy:
include_once/require_onceavoid multiple inclusions.
🏁 Summary
-
Use
includefor optional files,requirefor essential files. -
*_oncevariants prevent duplicate inclusion. -
Useful for headers, footers, menus, database connections, and reusable functions.
