Reputation: 152
i want write a code in php that go to dir "upload" and see if is a file that dont Exists in my db and remove this file if it find.
$like = scandir(upload);
$myFile1 = upload;
$myFile1 .= '/';
$myFile1 .= $like;
$rs = mysql_query('SELECT url from blog');
while(list($url) = mysql_fetch_row($rs))
{
if($like != $url){
unlink($myFile1);
}
}
its write me a eror Warning: unlink(upload/Array) [function.unlink]:
Upvotes: 1
Views: 1306
Reputation: 10732
scandir
returns an array of files; you'll need to step through that array, to check each one individually:
$like = scandir('upload');
foreach ($like as $thisFile) {
$rs = mysql_query("SELECT url FROM blog WHERE url='$thisFile'");
if (! mysql_num_rows($rs)) {
if($thisFile != "." and $thisFile != ".."){
unlink ('upload/' . $thisFile);
}
}
}
You're checking each file in that directory to see if it has an entry in the blog
table; if it doesn't, it's passed to unlink. I've not tested this code, but it should give you an idea about how it runs.
A couple of notes:
What if there are directories in the directory? You should add some checking to skip over them. Don't forget that you'll have ./
and ../
in there.
What if there's an entry in the blog
of ..\..\..\..\etc\passwd
? You should add some checking to make sure that $thisFile
isn't something you don't want to delete.
This is using mysql; that's deprecated, and you should look at migrating to mysqli
or PDO
for the query. You can also then convert the query into a prepared statement, which will help it run more efficiently.
Upvotes: 2