Alex Alex - 1 month ago 11
PHP Question

is it possible to read php file with file_get_contents?

I created web page which load ( just

)from url get request.I have done this before with
but it is dangerous because hacker can include file which is not from
.I tried this on
and it says bad request which is perfect but I want to be sure because actually I heard that
s is dangerous?I don't want to help hacker to read php file because I heard that it is possible with


file_get_contents() may be dangerous if you use user supplied data as a parameter and print its output. A malicious user may then use e.g. /etc/passwd to read all your server's user names. Or, he/she could use '..' as part of the file name to access files even if you prepend the name with an allowed path (e.g. "../../etc/passwd")

To prevent that from happening, you should always check user given values for validity, for example, that a file name or path is in an expected part of your file system, and so accessing only files that you want the user to access. PHP has a function to make relative paths (or paths that contains symbolic links) 'real': realpath().

After making a path 'real' you can check the path if it is in the expected part of the file system and then safely use it for file_get_contents().

$wanted = $_GET['path'];
$real = realpath('/var/www/user/accessible/' . $wanted);
if (strpos($real, '/var/www/user/accessible/') === 0) {
   echo file_get_contents($real);
} else {
   throw new Exception('not allowed to access this file');