Checking a string to see if file exists locally
<p>I have a question if I may. I have a variable named <code>$source</code> and this <em>should</em> contain a relative path to a file, for example <code>./uploads/2012/some-document.pdf</code></p>

<p>Now, this <code>$source</code> variable will contain user input, via $_GET and $_POST. I don't want people to enter URLs and I only want to do something if the file exists <strong>only</strong> on the local server.</p>

<p>My question is what is the best way to check if a file exists on the local server only?</p>

<hr>

<p>This is what I've got so far:</p>

<p>1) <code>file_exists</code> may return true depending on the server configuration, so I could use this alongside stripos to check if the first few charatcers of the string is http:// like so:</p>

<pre><code>if( file_exists($source) &amp;&amp; stripos($source,'http://')!==0 ) {
    echo 'File exists on local';
}
</code></pre>

<p>However, the downside would be I'd have to specify all the different URL types such as https://, http:// and ftp:// just to be safe.</p>

<p>2) I use <code>realpath</code> to get the absolute path of the file, and this returns false if it cannot be found. This seems to be pretty solid, but not 100% this is the best application for it</p>

<p>3) Use <code>preg_replace</code> to remove all URL mentions in the string first, and then simply use <code>file_exists</code>.  Whilst this would probably be the most secure, it would most likely be the most intensive and I'd prefer not to use this method.</p>
