RegEx找到"../"或"./"

arb*_*bme 0 php regex

我试图让正则表达式告诉我路径是否包含./../.这是为了检查用户是否超出他们的区域.如果输入包含正斜杠之前的一段时间,则不会被接受.

例如

/user/selected/path/ - Ok 
./user/selected/path/ - Failed 
../user/selected/path/ - Failed 
Run Code Online (Sandbox Code Playgroud)

正斜杠将替换为DIRECTORY_SEPERATOR,因此适用于unix和windows路径.

Pek*_*ica 6

检查".."的存在是该问题的不完美解决方案.

如果要阻止用户突破基本目录,请检查realpath()路径的结果(将考虑相对路径)是否仍在根路径下.

例:

$root = "/my/user/basepath";
$requested_path = $_GET["input"]; // or whatever

$real_path = realpath($root."/".$requested_path);

if (strpos($real_path, $root) !== 0)
 die ("Illegal path");
Run Code Online (Sandbox Code Playgroud)