semaxx
semaxx

Reputation: 53

PHP unlink without the ending (.jpg, .gif)

I have this code:

<?php
$filename = $_POST['showDeleteNummer'];
  if (file_exists("../Images/".$filename)) {
    @unlink($filename);
    echo('ja');
  }
  else{
    echo ('nein');
  }
?>

The problem is, that I don't know the ending of the file (.jpg, .png, .gif). Is there a code for deleting a file in the folder with a special name (without the ending)? There won't be another file with the same name.

Upvotes: 1

Views: 644

Answers (2)

andreashager
andreashager

Reputation: 667

Franz Gleichmanns answer would be one solution, but if the extension is .pdf or .doc? Better use glob() with a pattern for this solution (http://php.net/manual/de/function.glob.php).

$name = '/path/to/file/with/name';
$files = glob($name . '*');
var_dump($files);

This should give you an array of all files that are available with all kind of different extension. Then you can iterate through them an delete them.

Edit: With this code snippet you can tell glob which file ending it should search or mask.

$name = '/path/to/file/with/name';
$files = glob($name . '*.{jpg,png,gif}', GLOB_BRACE);
var_dump($files);

Upvotes: 3

Franz Gleichmann
Franz Gleichmann

Reputation: 3568

Just look if the file actually exists in the first place and you should be set.

$name = "picture";
if(file_exists("$name.png")) {
     unlink("$name.png");
}elseif(file_exists("$name.gif")) {
     unlink("$name.gif");
} elseif(file_exists("$name.jpg")) {
     unlink("$name.jpg");
}

Upvotes: 1

Related Questions