Getting a local file with file_get_contents 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-&gt;text(file_get_contents($path));
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.