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’:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create file2.php in folder ‘myGeeks’:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create file3.php in folder ‘myGeeks’:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create file4.php in folder ‘myGeeks’:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Create main.php outside folder:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.