Optional include in PHP

2019-05-31 15:52发布

I have a config file with the general configuration (in a git repo), and a local config file that overwrites configuration properties (ignored in the repo). Right now the local config file is included at the beginning of the config file:

include_once 'local_config.php';

But I would like the include to be conditional: only do it if the file local_config.php actually exists. I can do a enter link description here without problems, but first I would need to check if the file exists. So I tried get_include_path() but it returns a list of paths, and I would have to parse this list and check for every one.

Another option would be to just call include_once() and suppress the warnings, but it is even messier. Is there a simpler way to do a real optional include in PHP?

3条回答
狗以群分
2楼-- · 2019-05-31 16:15

Use the file_exists() predefined PHP function like so:

// Test if the file exists
if(file_exists('local_config.php')){
    // Include the file
    include('local_config.php');
}else{
    // Otherwise include the global config
    include('global_config.php');
}

Documentation here: http://php.net/manual/en/function.file-exists.php

查看更多
爷、活的狠高调
3楼-- · 2019-05-31 16:28

You can use stream_resolve_include_path($filename) if you have a PHP version higher than 5.3.2

http://php.net/stream_resolve_include_path

查看更多
再贱就再见
4楼-- · 2019-05-31 16:36
登录 后发表回答