我通过ftp_connect
和ftp_login
连接到FTP服务器。连接后,我会转到ftp_chdir
的目录。在目录中,我必须使用ftp_delete
删除文件名中包含“ub”字样的所有文件。因此,我必须以某种方式阅读每个文件名并仅删除那些在其文件名中包含“ub”的文件。我不知道该怎么做。请帮忙。感谢。
答案 0 :(得分:0)
如果使用交互式ftp命令行工具,则可以发出命令
mdel *ub*
但是低级协议不支持通配符操作;这是必须在客户端实现的东西,通过获取所有名称,与模式进行比较,并逐个删除,如你所说。您可能想要考虑使用命令行ftp编写脚本,而不是使用php?
答案 1 :(得分:0)
@Pekka的评论有一个可能的解决方案。另一个是使用glob
。
$files = glob('*ub*');
答案 2 :(得分:0)
foreach (glob("*ub*") as $file) {
ftp_delete('YOUR_CONNECTION', $file);
}
问候
答案 3 :(得分:0)
由于这个问题没有真正的答案,我将回答我的功能,允许通过ftp删除多个文件:
/**
* Delete multiple files on FTP server. Allowed wildcards are * and ?.
* @param resource $ftp_connection
* @param string $delete_pattern
* @param bool $case_sensitive Case sensitivity is by default
* @return bool|int Number of deleted files, FALSE on failure
*/
function ftp_mdelete($ftp_connection, $delete_pattern = "", $case_sensitive = TRUE){
if(!is_resource($ftp_connection) || strtolower(get_resource_type($ftp_connection)) !== "ftp buffer"){
trigger_error("First parameter for ftp_mdelete should be a valid FTP connection", E_USER_WARNING);
return FALSE;
}elseif(!is_string($delete_pattern) || !strlen($delete_pattern)){
trigger_error("Second parameter for ftp_mdelete should be a non-empty string", E_USER_WARNING);
return FALSE;
}
$raw_list = ftp_rawlist($ftp_connection, '.');
if(!is_array($raw_list)){
return FALSE;
}
$matched_count = 0;
$deleted_count = 0;
if($raw_list){
$delete_pattern = preg_quote($delete_pattern);
$delete_pattern = '/^'.str_replace(array('\*', '\?'), array('.*', '.'), $delete_pattern).'/S'.($case_sensitive?'':'i');
foreach($raw_list as $entry){
if($entry{0} === '-'){
$entry = preg_split("/[\s]+/S", $entry, 9);
$entry = $entry[8];
if(preg_match($delete_pattern, $entry)){
++$matched_count;
if(ftp_delete($ftp_connection, $entry)){
++$deleted_count;
}
}
}
}
unset($raw_list, $entry);
}
if($matched_count != $deleted_count && $deleted_count){
trigger_error("Only {$deleted_count} out of {$matched_count} files deleted.", E_USER_NOTICE);
}elseif($matched_count && !$deleted_count){
trigger_error("No files were deleted ({$matched_count} files matched given pattern).", E_USER_WARNING);
return FALSE;
}
return $deleted_count;
}
用法示例:
$ftp = ftp_connect('127.0.0.1');
ftp_login($ftp, 'user', 'pass');
ftp_chdir($ftp, 'dir');
$deleted = ftp_mdelete($ftp, '*ub*');
ftp_close($ftp);
echo "Number of deleted files: ".intval($deleted);