2

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?

Community
  • 1
  • 1
alexfernandez
  • 1,938
  • 3
  • 19
  • 30
  • 3
    Maybe I am thinking to simple, but a simple `if(file_exists($path)) {` is what you need. – SativaNL Apr 19 '12 at 08:57
  • See my comment below: get_include_path() might return something different than the current directory `.`, in which case I should look there: `if (file_exists($include_path . $path)) {}`. – alexfernandez Apr 19 '12 at 14:11

3 Answers3

4

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

Ben Carey
  • 16,540
  • 19
  • 87
  • 169
  • 1
    I don't think that is enough. How can I be sure if the include file is in the current directory? Perhaps the general config has been included from a different file which has called set_include_path() to a different directory. In that case I should look there: `if (file_exists($include_path . $path)) {}.` On my local system there are several different paths in `include_path`. – alexfernandez Apr 19 '12 at 14:10
  • Then loop through each of the paths with a `foreach` statement. You can also use PHP's `glob` function to list files from a directory. Does this help? – Ben Carey Apr 19 '12 at 14:46
  • That is exactly what I described and what I am trying desperately to avoid :) – alexfernandez Apr 19 '12 at 18:27
  • If you are testing if the file exists in multiple directories, the best and most efficient method is to use a `foreach` loop! Would you like me to write an example? – Ben Carey Apr 20 '12 at 06:43
1

you can just use file_exists()

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

RiquezJP
  • 261
  • 3
  • 12
1

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

Paul Holt
  • 51
  • 1
  • 6