我刚刚编写了一个ftp_glob
函数,因为我在项目中也需要它。它的工作方式与glob()完全相同,但没有任何选项。
使用示例
$ftp = ftp_connect($server, $port, 90);
ftp_login($ftp, $login, $password);
ftp_pasv($ftp, true);
$list = ftp_glob($ftp, "/sample/*.csv");
代码
function ftp_glob($resource, $pattern)
{
$dir_patterns = explode('/', ltrim($pattern, '/'));
if (count($dir_patterns) == 0)
{
return array ();
}
$paths_to_check = array (ftp_pwd($resource));
return ftp_glob_rec($resource, $dir_patterns, $paths_to_check);
}
function ftp_glob_rec($resource, $dir_patterns, $paths_to_check)
{
$matching_paths = array();
$pattern = array_shift($dir_patterns);
foreach ($paths_to_check as $path)
{
$list = ftp_nlist($resource, $path);
if ($list === false)
{
continue ;
}
foreach ($list as $file)
{
if (in_array($file, array('.', '..')))
{
continue ;
}
if (match($file, $pattern) > 0)
{
$matching_paths[] = rtrim($path, '/') . '/' . $file;
}
}
}
if (count($dir_patterns) == 0)
{
return $matching_paths;
}
return ftp_glob_rec($resource, $dir_patterns, $matching_paths);
}
function match($string, $pattern, $a = 0, $b = 0, $options = '')
{
if ((!isset($string[$a])) && (!isset($pattern[$b])))
{
return 1;
}
if (strpos($options, 'x') !== false)
{
if (($string[$a] == "\n") || ($string[$a] == "\t") || ($string[$a] == "\r") || ($string[$a] == " "))
{
return (match($string, $pattern, ($a + 1), $b, $options));
}
if (($pattern[$b] == "\n") || ($pattern[$b] == "\t") || ($pattern[$b] == "\r") || ($pattern[$b] == " "))
{
return (match($string, $pattern, $a, ($b + 1), $options));
}
}
if ((isset($pattern[$b])) && ($pattern[$b] == '*'))
{
if (isset($string[$a]))
{
return (match($string, $pattern, ($a + 1), $b, $options) + match($string, $pattern, $a, ($b + 1), $options));
}
else
{
return (match($string, $pattern, $a, ($b + 1), $options));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '?'))
{
return (match($string, $pattern, ($a + 1), ($b + 1), $options));
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($pattern[$b] == '\\'))
{
if ((isset($pattern[($b + 1)])) && ($string[$a] == $pattern[($b + 1)]))
{
return (match($string, $pattern, ($a + 1), ($b + 2), $options));
}
}
if ((isset($string[$a])) && (isset($pattern[$b])) && ($string[$a] == $pattern[$b]))
{
return (match($string, $pattern, ($a + 1), ($b + 1), $options));
}
return 0;
}