时间:2018-12-04 来源:风信官网 点击: 875次
<?php
/**
* Example for the article at medium.com
* Created by Igor Data.
* User: igordata
* Date: 2017-01-23
* @link https://medium.com/@igordata/php-running-jpg-as-php-or-how-to-prevent-execution-of-user-uploaded-files-6ff021897389 Read the article
*/
/**
* 检查某个路径是否在指定文件夹内。若为真,返回此路径,否则返回 false。
* @param String $path 被检查的路径
* @param String $folder 文件夹的路径,$path 必须在此文件夹内
* @return bool|string 失败返回 false,成功返回 $path
*
*/
function checkPathIsInFolder($path, $folder) {
if ($path === '' OR $path === null OR $path === false OR $folder === '' OR $folder === null OR $folder === false) {
/* 不能使用 empty() 因为有可能像 "0" 这样的字符串也是有效的路径 */
return false;
}
$folderRealpath = realpath($folder);
$pathRealpath = realpath($path);
if ($pathRealpath === false OR $folderRealpath === false) {
// Some of paths is empty
return false;
}
$folderRealpath = rtrim($folderRealpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$pathRealpath = rtrim($pathRealpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if (strlen($pathRealpath) < strlen($folderRealpath)) {
// 文件路径比文件夹路径短,那么这个文件不可能在此文件夹内。
return false;
}
if (substr($pathRealpath, 0, strlen($folderRealpath)) !== $folderRealpath) {
// 文件夹的路径不等于它必须位于的文件夹的路径。
return false;
}
// OK
return $path;
}