About

This is a PHP example illustrating how path traversals can be mitigated.

Code

<?php
 
# Get the user-supplied path.
$userPath = $_POST['path'];
 
# The document root path.
$documentRoot = realpath("/var/www");
 
# Get the path from the user-supplied path.
$pathPart = pathinfo($userPath);
# Compare the "real" directory path of the user supplied path with the document root.
if(realpath($pathPart['dirname']) != $documentRoot)
    die;