简体   繁体   中英

scandir for files for users

I've created a pages dashboard for my content management system, and well I am trying to iterate the scandir method and my conditions are not working. Can someone explain why?

$pages = scandir('../',0);
foreach($pages as $page){
  if($page !== "." OR $page !== ".." OR $page !== "admin" OR $page !== "admin.php" OR $page !== "kms_kontent" OR !is_dir('../'.$page)){
        $extension = explode('.',$page);
        $extension = end($extension);
        $page = str_replace('.'.$extension,'',$page);
     echo '<div class="row"><ul><li class="fifths">'.$page.'</li><li class="fifths"></li></ul></div>';
  }
}

It's echoing all contents

--public_html
   -admin.php #don't show
   -admin #don't show
   -kms_content #don'tshow
   -index.php #show
   -shop.php #show

Also it's showing . and .. which I don't want to show either.

The logic is flawed. To see why, let's assume you have just this comparison:

$page !== "." OR $page !== ".."

The condition is satisfied if page isn't . or if page isn't .. ; if the page is . it will not be equal to .. and vice versa. In other words, the condition is always satisfied.

What you want is that the condition is satisfied only if page is neither . nor .. ; so:

!($page === '.' || $page === '..')

Following DeMorgan's law:

$page !== '.' && $page !== '..'

An array of possible values could be used to simplify the code even more:

$invalid_pages = [".", "..", "admin", "admin.php", "kms_kontent"];

if (!in_array($page, $invalid_pages) && !is_dir('../'.$page)) {
}
if (
    $page !== "." OR
    $page !== ".." OR
    $page !== "admin" OR
    $page !== "admin.php" OR
    $page !== "kms_kontent" OR
    !is_dir('../'.$page)
) {

Because you are using OR , the if will go true when any of the conditions is true. So if $page is admin it will go false for $page !== "admin" but true to all others, and it won't work. You should use && or AND .

But instead, you could clean up that code a little bit using arrays. For instance:

$filter = ['.', '..', 'admin', 'admin.php', 'kms_kontent'];
$pages = scandir('../', 0);
foreach ($pages as $page) {
    if (!in_array($page, $filter) && !is_dir("../$page")) {
        ...
    }
}

It does the same thing, but the code looks cleaner and more items can be added more easily.

使用AND或&&代替OR!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM