Check line to see if file exists locally

I have a question if I can. I have a variable with a name $source, and it should contain a relative path to the file, for example./uploads/2012/some-document.pdf

Now this variable $sourcewill contain user input through $ _GET and $ _POST. I do not want people to enter URLs, and I only want to do something if the file exists only on the local server.

My question is the best way to check if a file exists on the local server?


This is what I still have:

1) file_existscan return true depending on the server configuration, so I could use this together with stripos to check if the first few charatcers are http: // lines as follows:

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

However, the downside would be that I would have to specify all the different types of URLs, such as https: //, http: // and ftp: //, to be safe.

2) I use realpathto get the absolute path to the file, and this returns false if it cannot be found. It seems pretty solid, but not 100% is the best app for him.

3) Use preg_replaceto remove all URLs in the first line and then just use file_exists. Although this would probably be the safest, it would most likely be the most intense, and I would prefer not to use this method.

+5
source share
2 answers

In addition to the other answers, you can reject the paths that use the circuit, simply with:

if (parse_url($path, PHP_URL_SCHEME)) {
    // has something:// so ignore
}

, php://, zlib:// ..

file://:

file_exists('file://' . $path);
+3

realpath() ( file_exists). URL- , , .

+2

All Articles