Sanitize file path in PHP Sanitize file path in PHP php php

Sanitize file path in PHP


realpath() will let you convert any path that may contain relative information into an absolute path...you can then ensure that path is under a certain subdirectory that you want to allow downloads from.


Use basename rather than trying to anticipate all the insecure paths a user could provide.


Solution by the OP:

$baseDir = "/home/gsmcms/public_html/central/app/webroot/"; $path = realpath($baseDir . $_GET['file']); // if baseDir isn't at the front 0==strpos, most likely hacking attempt if(strpos($path, $baseDir) !== 0 || strpos($path, $baseDir) === false) {    die('Invalid Path'); } elseif(file_exists($path)) {    echo file_get_contents($path); } else {    header('HTTP/1.1 404 Not Found');    echo "The requested file could not be found"; }