How to Import All PHP Scripts in a Folder

One powerful feature of PHP is its ability to "include" other PHP files that contain further scripts and functions. Because of this, you don't have to duplicate your code over and over --- you can just include the other PHP file that contains it. By default, PHP includes only a single file at a time, but by using PHP's ability to read a directory you can loop over the files within it and include all of the PHP scripts in turn.

Instructions

    • 1

      Create a new PHP file in the parent directory of the folder that contains the scripts you want to import. After opening it in a text editor, add "<?php" as the first line and "?>" as the last line.

    • 2

      Link the folder containing your PHP scripts to a variable named "$includefolder" and put that code on the second line of your PHP file. If the folder with the scripts on it is called "includes," you would write:

      $includefolder = "includes/";

    • 3

      Open the folder by using an "if" statement and PHP's "opendir()" function. To do this, add a third line to your PHP script that initializes the statement:

      if($includefolderh = opendir($includefolder)) {

      Remember to add another closing brace ("}") on the second to last line of the PHP file, so that the statement is properly terminated.

    • 4

      Write the following code on the fourth line, immediately following the initialization of the if() statement:

      while(($file = readdir($includefolderh)) !== false) { if(strpos($file,".php")!==false) { include $includefolder . $file; } }

      Type this code exactly, or cut and paste it into your PHP file. It will loop through the files in the given directory and, if they are PHP files (as marked by the ".php" file extension), it will include them in your script.

Related Searches:

References

Comments

Related Ads

Featured