user3818265
user3818265

Reputation: 81

Checking if file exists in directory

I have a php script to check whatever files exist or not in a Linux system.

If I delete the file from the directory, the script still gives me true when I call the file_exists function, but the directory is empty.

It seems scandir function scan dots in the directory in result giving me file exits statement.

Also, I tried glob function I’m getting same result.

Here is my code:-

<?php
while(true)
{

  foreach (scandir("/var/log/phplogs/iplogs/") as $filename)
  {

    if(file_exists("/var/log/phplogs/iplogs/$filename"))
    {
      echo "file exist\n";
    }
    else
    {
      echo "file doesn't exist\n";
    }
  }
}

?>

Upvotes: 2

Views: 2455

Answers (3)

lowerends
lowerends

Reputation: 5267

You can use this code to skip the . and .. results from the scandir result:

<?php

$files = array_filter(scandir('/var/log/phplogs/iplogs/'), function($item) {
    return $item !== '.' && $item !== '..';
});

foreach ($files as $filename)
{
    if(file_exists("/var/log/phplogs/iplogs/$filename"))
    {
        echo "file exist\n";
    }
    else
    {
        echo "file doesn't exist\n";
    }
}

By modifying the array_filter callback, you can also leave out other files and even subdirectories.

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

Check using is_file() to see if it's a file and not a directory. Also, clearstatcache():

while(true)
{
  clearstatcache();

  foreach(scandir("/var/log/phplogs/iplogs/") as $filename)
  {
    if(is_file("/var/log/phplogs/iplogs/$filename"))
    {
      echo "file exist\n";
    }
    elseif(!is_dir("/var/log/phplogs/iplogs/$filename"))
    {
      echo "file doesn't exist\n";
    }
  }
}

Upvotes: 0

oliakaoil
oliakaoil

Reputation: 1689

I don't think there is a built-in feature of scandir that will help with this issue. However you could simply do something like this:

$filtered_contents = array_diff(scandir("/var/log/phplogs/iplogs/"), array('..', '.'));

Then use $filtered_contents in your foreach loop rather than the scandir call.

Upvotes: 0

Related Questions