Thursday, September 4, 2025
HomeLanguagesHow to include() all PHP files from a directory ?

How to include() all PHP files from a directory ?

Given list of PHP files in a directory and the task is to include all files from a directory. In order to include all PHP files from directory at once need a foreach-loop.

Example: This example contains four PHP files (file1.php, file2.php, file3.php, file4.php) in a directory. Create one file named as main.php which contains PHP code to include files.

Create file1.php in folder ‘myGeeks’:




<?php 
echo "1st File Included Successfully<br>";
?>


Create file2.php in folder ‘myGeeks’:




<?php 
echo "2nd File Included Successfully<br>";
?>


Create file3.php in folder ‘myGeeks’:




<?php 
echo "3rd File Included Successfully<br>";
?>


Create file4.php in folder ‘myGeeks’:




<?php 
echo "4th File Included Successfully<br>";
?>


Create main.php outside folder:




<?php
foreach (glob("folder/*.php") as $filename) {
    include $filename;
}
?>


Run on Windows platform:

  • Folder myGeeks which contains all files:
  • Folder htdocs contains main.php file:
  • Run on Browser:

Run on Ubuntu platform:

  • Folder ‘Desktop/folder’ which contains all files:
  • Folder ‘Desktop’ contains main.php file:
  • Run on Terminal:
  • Output:
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS