title: How to safely evaluate a file's contents before including it in PHP
body: <p>I am using PHP files returning arrays as a means of configuration.
  To process these configuration files I made a class to search the provided configuration directories for PHP files and store their values in a configuration container using <code>include()</code>.</p>
  <p>Now I was just wondering about the safety of this method.
  What if somebody puts malicious code inside one of these files?</p>
  <p>What would be the safest way to evaluate these files before including them and potentially triggering unwanted side effects?</p>
  <p>I was thinking about using <code>file_get_contents()</code> to load the file as a string and look for any function calls, but I don't want to restrict users from using functions to resolve, for instance, conditional configuration values.</p>
  <p>This is the current code, just for an idea of the workings:</p>
  <pre><code>public function load(): void
  {
      $iterator = $this-&gt;createFinder()-&gt;getIterator();
  
      foreach ($iterator as $file) {
          $config = include $file;
  
          if (! is_array($config)) {
              throw new \RuntimeException(&quot;Invalid config \&quot;{$file-&gt;getRealPath()}\&quot;, Config files should return an array.&quot;);
          }
  
          $this-&gt;config[$file-&gt;getBasename()] = $config;
      }
  }
  
  private function createFinder(): Finder
  {
      $this-&gt;finder = (new Finder())
          -&gt;in($this-&gt;directories)
          -&gt;files()
          -&gt;name('*.php');
  
      return $this-&gt;finder;
  }
  
  </code></pre>