How can i delete certain files from php in a directory

I want to deletes files in my date('m-d-Y').'/' directory that contain ".5010." in there filename

Is it by:
$filename= "%5010%";
unlink(filename,path)

Open in new window


Because this didnt work?
LVL 1
Jazzy 1012Asked:
Who is Participating?
 
Julian HansenCommented:
unlink works on one file at a time so you will need to iterate over all files in the folder, check if they match
This is the simplest - not the fastest - method of doing it

$folder = 'path/to/files/';
foreach(glob($folder . '*5010*') as $path) {
   if (is_file($path) && is_writable($path)) {
     unlink($path);
   }
}

Open in new window

1
 
zephyr_hex (Megan)DeveloperCommented:
You should check to make sure you have permissions to delete the file using is_writable()

is_writable ( string $filename )

Open in new window


Where $filename includes the full path to the file.
1
 
Jazzy 1012Author Commented:
I can delete them manually so I think it is fine
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
zephyr_hex (Megan)DeveloperCommented:
But you are not PHP.  You need to check whether it works from PHP because it's PHP that's doing the deleting, not you.
1
 
Jazzy 1012Author Commented:
Okayy thanks
0
 
Brian TaoSenior Business Solutions ConsultantCommented:
The unlink() function doesn't support wildcard.
One way to delete all files with wildcard is to use the glob function.  In your case:
<?php
foreach (glob("*.5010.*") as $filename) {
   unlink($filename);
}
?>

Open in new window

or you can use one of system(), exec() or shell_exec()
1
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.