<?php
/**
* Check a path and prevent from hack
*
* @param string $path Path to protect
* @param string $mod Mode : "dir" or "file" (default = dir)
* @return string Protected path
*/
function path_prevent($path = "./", $mod = "dir")
{
//Prevent from $mod error
if($mod != "file")
$mod = "dir";
//Protect the string (set as local ./ and remove /../)
$path = realpath($path);
$path = str_replace(realpath("."), "", $path);
//Prevent from missing last /
if($mod == "dir")
$path .= "/";
//Converte to "/" unix slash
$path = str_replace("\\","/", $path);
//Remove //
$path = str_replace("//", "/", $path);
//It could be the ./ dir, so empty string
if($path == "")
$path = "./";
//Remove the / if it's the first char
if(substr($path, 0, 1) == "/")
$path = substr($path, 1);
//Check validity
if($mod == "file")
{
if(!is_file("./".$path))
$path = false;
else
if($path == "")
$path = false;
}
else //$mod == "dir"
{
if(!is_dir("./".$path))
$path = false;
else
if($path == "")
$path = false;
}
return $path;
}
?>