HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Getting a local file with file_get_contents

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
localfilewithgettingfile_get_contents

Problem

my url is like page.php?path=content/x/y/z/aaa.md. Is the following php code secure?

include "Parsedown.php";

function path_purifier($path) {
  if(substr($path, 0, 8) !== "content/")
    return null;
  if (strpos($path,'..') !== false)
    return null;
  return "./" . $path;
}

$parsedown = new Parsedown();
$path = $_GET['path'];
$path = path_purifier($path);
echo $parsedown->text(file_get_contents($path));

Solution

As @KIKO stated, this is a bit dangerous to use relative paths (here, contents/ which is ./contents) because if your php script becomes included or reused, relative path (.) may points to a different location.

You can create a constant or put that absolute path in a config file. At the end, you'll check that the absolute path given by user is beginning by the expected absolute path:

define('THIS_ROOT','/this/is/my/file/root/');

function path_check($path) {
   return strncmp(THIS_ROOT, realpath($path), strlen(THIS_ROOT)) == 0;
}


If the given $path does not exist, realpath will return false so this check manages both security and resource existence.

Code Snippets

define('THIS_ROOT','/this/is/my/file/root/');

function path_check($path) {
   return strncmp(THIS_ROOT, realpath($path), strlen(THIS_ROOT)) == 0;
}

Context

StackExchange Code Review Q#83428, answer score: 5

Revisions (0)

No revisions yet.