title: How to use file_get_contents safely?
body: <p>I am making a basic PHP source viewer for my blog's example code folder.</p>
  
  <pre><code>&lt;?php
  
  if (isset($_GET['file']))
  {
      header('Content-type: text/plain');
      $filename = realpath($_GET['file']);
      if (startsWith($filename, dirname(__FILE__)))
      {
          echo file_get_contents($filename);
      }
  }
  
  function startsWith($haystack, $needle)
  {
      $length = strlen($needle);
      return (substr($haystack, 0, $length) === $needle);
  }
  
  ?&gt;
  </code></pre>
  
  <p>Is what I have here sufficient that it will never allow a file outside the directory in which this script is located, or subdirectories of this script's directory, to be viewed? I'm guessing there's a better solution than startsWith too, for checking whether a path is a descendant of a particular directory?</p>