2011-04-02 108 views
4

我有一个目录和一个动态文件名。是否有任何功能可以用来确保不可能从指定的目录中跳出?如何使用php正确建立文件路径?

例如:

secure_path('/tmp/', 'file.txt') -> /tmp/file.txt 
secure_path('/tmp/', '../file.txt') -> /tmp/file.txt 

回答

2

如果你只在单个目录的工作,而不是子目录下面你可以做

$file = "/tmp/".basename($input); 

这应该给你在任何路径结尾的文件名在输入中给出,并将其追加到你想要的目录。

0

我真的不知道该怎么../file.txt应该变成/tmp/file.txt在你的榜样,但检查的路径是否是另一个的子路径,使用realpath用一个简单的对比:

$path = '../foo'; 
$allowedPath = '/tmp/'; 

$path = realpath($path); 
if (substr($path, 0, strlen($allowedPath)) !== $allowedPath) { 
    // path is not within allowed path! 
} 
2

使用realpath()获得路径的法服形式,并消除任何../ -s。然后验证它是否包含要包含它的目录的完整路径。

如:

$path = "/tmp/file.txt"; 
$directory = "{full path of your files directory}"; 

if (strpos(realpath($path), $directory) === 0) { 
    // path OK 
} 
else { 
    // path not ok 
}