The get_include_path() function is used to return the file include path in the current PHP configuration. These paths are the paths used by PHP when looking for files in include , require and other functions. You can add multiple directories to the file include paths, which PHP will look for in order.
string get_include_path(void)
This function has no parameters and returns a string containing the paths, separated by the operating system's default separator (colon in UNIX systems and semicolon in Windows systems ; ).
To better understand get_include_path() , let's take a look at a simple example:
<?php
// Get the current file including path
$currentIncludePath = get_include_path();
echo "The current file contains the path:$currentIncludePath";
?>
In this code, we call get_include_path() and save the return value in the $currentIncludePath variable and output it to the screen. After executing this code, you will see that all files in the current PHP configuration contain paths.
We can combine the get_include_path() and set_include_path() functions to dynamically set the file's include path. The set_include_path() function is used to set a new file include path, which will replace the previous path, or you can add a new path based on the original path.
<?php
// Get the current include path
$currentIncludePath = get_include_path();
echo "The current file contains the path:$currentIncludePath\n";
// Set new file including path
$newIncludePath = "/var/www/includes";
set_include_path($newIncludePath . PATH_SEPARATOR . $currentIncludePath);
// Output updated include path
echo "The updated file contains the path:" . get_include_path() . "\n";
// Now we can include the file in the new path
include('myfile.php');
?>
In this example, we first get the current file include path. Then use the set_include_path() function to dynamically add a new path /var/www/includes and combine it with the original path. With PATH_SEPARATOR we ensure that path separators differ between different operating systems.
The updated path will affect all subsequent include or require calls, so we can load the myfile.php file in the new path.
You can also add multiple paths to include paths and use get_include_path() to verify those paths. PHP looks for files in the order of paths, which means that if the files are in multiple paths, PHP loads the first found file.
<?php
// Set multiple paths
$newIncludePath = "/var/www/includes:/usr/local/lib";
set_include_path($newIncludePath);
// Output a new include path
echo "The new file contains the path is:" . get_include_path() . "\n";
// Now we can find files in multiple paths
include('myfile.php');
?>
In this example, we add two directories /var/www/includes and /usr/local/lib to the file include path and update the include path via set_include_path() . By using the path output from get_include_path() , you can verify the order in which files are loaded.