-2

I am trying to unlink files in a Directory which have no extensions.

I did following, but did not work:

      $fileInfo = pathinfo($this->outputPath);
      if($fileInfo['extension'] == NULL)
      {
          unlink($fileInfo['dirname'].$fileInfo['basename']);
      }
Olipol
  • 315
  • 1
  • 9
  • 19

2 Answers2

2

As @CBroe noticed in comments:

Your comparison with NULL is just wrong here.

Check for empty'ness instead:

  $fileInfo = pathinfo($this->outputPath);

  if(empty($fileInfo['extension']))
  {
      unlink($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $fileInfo['basename']);
  }

Also, you missed a DIRECTORY_SEPARATOR between the dirname and the basename.


Update: As @hassan pointed out, empty is not the proper way to check for this either. That's because of directories . and .. on unix-like systems will pass this test, which is not desired.

So, the proper way to check for files without extension would be:

  if(isset($fileInfo['extension']) === false)
  {
      unlink($fileInfo['dirname'] . DIRECTORY_SEPARATOR . $fileInfo['basename']);
  }
Joe Black
  • 867
  • 1
  • 9
  • 10
2

according to the pathinfo manual :

Note:
If the path does not have an extension, no extension element will be returned (see second example below).

so you need to check if the returned value has the extension element using isset , note that using empty will pass the dot directories in unix systems, for example if you are iterating some directory empty will consider the . and .. directories as an empty extension elements

// check if not isset
if(isset($fileInfo['extension']) === false) {
    // perform some action
}

or if in the future you want to perform some complex search [eg: recursive search for files that does not have extensions] you may use FilesystemIterator

foreach (new FilesystemIterator($dir) as $fileInfo) {
    // check if some file extension is null
    if ($fileInfo->getExtension() == null) {
        // perform some action
    }
}
hassan
  • 7,812
  • 2
  • 25
  • 36