你错过了/
两次尾随。在glob()
你/home/user/public_html*.*
作为论点给予时,我认为你的意思是/home/user/public_html/*.*
。
这就是为什么我打赌没有与您表中的文件匹配的原因。这也不会出错,因为语法很好。
然后你在哪里unlink()
再次这样做......你的论点home/user/public_htmltestfile.html
应该是home/user/public_html/testfile.html
。
我喜欢这种语法风格:"{$directory}/{$file}"
因为它更短且更具可读性。如果/丢失,您会立即看到它。您也可以将其更改为$directory . "/" . $file
,您喜欢它。一行条件语句也是如此。所以它来了。
<?php
$directory = "/home/user/public_html";
$files = glob("{$directory}/*.*");
foreach($files as $file)
{
$sql = mysql_query("SELECT id FROM files WHERE FileName=\"{$file}\";");
if(mysql_num_rows($sql) == 0)
{
unlink("{$directory}/{$file}");
}
}
?>
编辑:您要求递归。来了。。
您需要创建一个可以使用路径作为参数运行一次的函数。然后,您可以从该函数内部的子目录中运行该函数。像这样:
<?php
/*
ListDir list files under directories recursively
Arguments:
$dir = directory to be scanned
$recursive = in how many levels of recursion do you want to search? (0 for none), default: -1 (for "unlimited")
*/
function ListDir($dir, $recursive=-1)
{
// if recursive == -1 do "unlimited" but that's no good on a live server! so let's say 999 is enough..
$recursive = ($recursive == -1 ? 999 : $recursive);
// array to hold return value
$retval = array();
// remove trailing / if it is there and then add it, to make sure there is always just 1 /
$dir = rtrim($dir,"/") . "/*";
// read the directory contents and process each node
foreach(glob($dir) as $node)
{
// skip hidden files
if(substr($node,-1) == ".") continue;
// if $node is a dir and recursive is greater than 0 (meaning not at the last level or disabled)
if(is_dir($node) && $recursive > 0)
{
// substract 1 of recursive for ever recursion.
$recursive--;
// run this same function again on itself, merging the return values with the return array
$retval = array_merge($retval, ListDir($node, $recursive));
}
// if $node is a file, we add it to the array that will be returned from this function
elseif(is_file($node))
{
$retval[] = $node;
// NOTE: if you want you can do some action here in your case you can unlink($node) if it matches your requirements..
}
}
return $retval;
}
// Output the result
echo "<pre>";
print_r(ListDir("/path/to/dir/",1));
echo "</pre>";
?>