-1

I have this code:

@unlink($sMediaDir . $iLastID . '' . '.jpg');

How to delete files regardless their extensions? And make it work also with .png, .bmp etc?

PHP: Delete a file with any extension? is not exactly what I am looking for. Thanks!

Community
  • 1
  • 1
Tompo
  • 15
  • 6
  • 2
    unlink() requires an actual filename. it has no wildcard/globbing support. you'd need to `glob()` your wildcard filenames first, then loop on the resulting array and unlink each matched file individually. – Marc B May 22 '14 at 19:48
  • You actually have `. '' .` in your code? – nl-x May 22 '14 at 19:49
  • DOS command: `delete *.*` --- "Are you sure *Y/N*" - enter. Even `del.` used to work. So, `*.*` should apply with [`glob()`](http://www.php.net/manual/en/function.glob.php). *Gotta love nostalgia.* – Funk Forty Niner May 22 '14 at 19:49
  • Dont use error surpressing. It's surprisingly slow, and not the way to go. Use file_exists() first – Martijn May 22 '14 at 19:50
  • How is http://stackoverflow.com/questions/10149101/php-delete-a-file-with-any-extension not what you are looking for? The accepted answer of that question is exactly what you're looking for. – nl-x May 22 '14 at 19:50
  • Yes, I have . '' . and don't know what it means... :) – Tompo May 22 '14 at 19:51
  • You don't know what `. '' .` is, and you're about to delete files from the filesystem? Euh.... yeah. hmmm. *sigh* – nl-x May 22 '14 at 19:52
  • nl-x, this solution is for files with certain names: "files profiles/bb-x62.foo", "profiles/bb-x62.bar". – Tompo May 22 '14 at 19:54
  • I'm about to delete images from server. Of course I have copies. – Tompo May 22 '14 at 19:56
  • @user3650459 I'm not touching this one with a 10-foot pole. – nl-x May 22 '14 at 19:56

1 Answers1

0

You can use glob() to find files to delete them

$files = glob($sMediaDir . $iLastID .'.*'); // Look for all files starting with $iLastId
if( count($files)!==0 ){
    // If files are found, loop through the array to delete them:
    foreach($files as $k=>$file){
         unlink($sMediaDir.$file);
    }
}

Im not entirely sure about the value of your variables, but you catch my drift :)

Martijn
  • 15,791
  • 4
  • 36
  • 68
  • the if count is totally useless – nl-x May 22 '14 at 19:55
  • It's totally not. You try a foreach on a empty array ;) Apart from the fast that `count()` is fast, no need for a slower foreach if no items – Martijn May 22 '14 at 19:56
  • Thanks, I'll try. I hoped that there's more simple solution like for example @unlink($sMediaDir . $iLastID . '' . '.*'); – Tompo May 22 '14 at 20:00
  • @Marijn: you will not get a 'nonset' array. In the event no file is found, you will have an empty array (there is NO problem with running an empty array through foreach). Only in the unlikely event of an error, then glob will return `false`. But then that won't be caught by your `if`, since you're using `!== 0`. – nl-x May 22 '14 at 20:03