簡體   English   中英

您如何使用PHP檢查文件是否在某個目錄中?

[英]How do you check if a file is in a certain directory using PHP?

使用PHP訪問文件時,可以使用“ ..”從目錄中轉出,這可能會導致安全風險。 有什么方法可以驗證文件是否在指定目錄中? 似乎沒有內置函數。

這不是檢查文件是否在預期位置的安全方法。您應該執行以下操作。

$base     = '/expected/path/';
$filename = realpath($filename);
if ($filename === false || strncmp($filename, $base, strlen($base)) !== 0) {
    echo 'Missing file or not in the expected location';
}
else {
    echo 'The file exists and is in the expected location';
}

php.net上有一個很好的例子

http://php.net/manual/zh/function.file-exists.php

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM