Bird
Raised Fist0
PHPprogramming~20 mins

Directory operations in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Directory Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code listing directory contents?
Consider this PHP code that reads and prints the names of files in a directory.
PHP
<?php
$dir = 'testdir';
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
      echo "$file\n";
    }
    closedir($dh);
  }
}
?>
ALists only files in 'testdir' excluding '.' and '..'
BLists all files and directories including '.' and '..' in 'testdir' each on a new line
CThrows a runtime error because opendir is not used correctly
DOutputs nothing because the directory is not opened
Attempts:
2 left
💡 Hint
Remember readdir returns '.' and '..' entries by default.
❓ Predict Output
intermediate
2:00remaining
What does this PHP code output when filtering directory files?
This PHP code lists only files (not directories) inside 'myfolder'. What is the output?
PHP
<?php
$dir = 'myfolder';
$files = [];
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
      if ($file !== '.' && $file !== '..' && is_file($dir . DIRECTORY_SEPARATOR . $file)) {
        $files[] = $file;
      }
    }
    closedir($dh);
  }
}
echo count($files);
?>
AThrows a warning because DIRECTORY_SEPARATOR is undefined
BPrints the total number of entries including directories inside 'myfolder'
CPrints 0 because is_file always returns false here
DPrints the number of files (not directories) inside 'myfolder'
Attempts:
2 left
💡 Hint
is_file checks if the path is a regular file, not a directory.
❓ Predict Output
advanced
2:00remaining
What error does this PHP code raise when trying to remove a directory?
This code tries to remove a directory named 'oldfolder'. What error or output occurs?
PHP
<?php
$dir = 'oldfolder';
rmdir($dir);
echo "Removed";
?>
AWarning: rmdir(): Directory not empty if 'oldfolder' has files
BFatal error because rmdir requires a second argument
CNo output because rmdir silently fails
DRemoved printed even if directory does not exist
Attempts:
2 left
💡 Hint
rmdir only removes empty directories.
❓ Predict Output
advanced
2:00remaining
What is the output of this PHP code creating a directory?
This PHP code tries to create a directory 'newdir' with permissions 0755. What is the output?
PHP
<?php
$dir = 'newdir';
if (mkdir($dir, 0755)) {
  echo "Created";
} else {
  echo "Failed";
}
?>
APrints nothing because mkdir returns void
BThrows a syntax error because 0755 is not a valid permission
CPrints 'Created' if directory does not exist and is created successfully
DPrints 'Failed' if directory already exists
Attempts:
2 left
💡 Hint
mkdir returns true on success, false on failure.
🧠 Conceptual
expert
2:00remaining
How many items are in the array after this PHP directory scan?
This PHP code scans a directory and filters out '.' and '..'. How many items does the array contain?
PHP
<?php
$dir = 'sampledir';
$items = scandir($dir);
$filtered = array_filter($items, fn($item) => $item !== '.' && $item !== '..');
echo count($filtered);
?>
ANumber of all files and directories inside 'sampledir' excluding '.' and '..'
BNumber of files only inside 'sampledir'
CAlways 0 because array_filter removes all items
DNumber of items including '.' and '..'
Attempts:
2 left
💡 Hint
scandir returns all entries including '.' and '..'.

Practice

(1/5)
1. Which PHP function is used to create a new directory?
easy
A. mkdir()
B. rmdir()
C. opendir()
D. closedir()

Solution

  1. Step 1: Understand directory creation functions

    In PHP, mkdir() is the function designed to create new directories.
  2. Step 2: Differentiate from other directory functions

    rmdir() removes directories, opendir() opens directories, and closedir() closes them.
  3. Final Answer:

    mkdir() -> Option A
  4. Quick Check:

    Create directory = mkdir() [OK]
Hint: Create folders with mkdir() function in PHP [OK]
Common Mistakes:
  • Confusing mkdir() with rmdir()
  • Using opendir() to create folders
  • Trying to create folder without mkdir()
2. Which of the following is the correct syntax to remove an empty directory named temp in PHP?
easy
A. delete('temp');
B. remove_dir('temp');
C. rmdir('temp');
D. rm('temp');

Solution

  1. Step 1: Identify the correct function for removing directories

    PHP uses rmdir() to remove empty directories.
  2. Step 2: Check syntax correctness

    The syntax rmdir('temp'); correctly removes the directory named 'temp'. Other options are not valid PHP functions.
  3. Final Answer:

    rmdir('temp'); -> Option C
  4. Quick Check:

    Remove empty folder = rmdir() [OK]
Hint: Use rmdir('foldername') to delete empty folders [OK]
Common Mistakes:
  • Using non-existent functions like remove_dir()
  • Trying to delete non-empty folders with rmdir() without clearing
  • Syntax errors like missing quotes or semicolons
3. What will be the output of the following PHP code?
$dir = 'myfolder';
if (is_dir($dir)) {
  $handle = opendir($dir);
  while (($file = readdir($handle)) !== false) {
    echo $file . ' ';
  }
  closedir($handle);
} else {
  echo 'Directory not found';
}
medium
A. Syntax error
B. Only files inside 'myfolder' without '.' and '..'
C. Directory not found
D. List of all files and folders inside 'myfolder' including '.' and '..'

Solution

  1. Step 1: Check if directory exists

    The code uses is_dir() to check if 'myfolder' exists. If it does, it proceeds to open it.
  2. Step 2: Read directory contents with readdir()

    The readdir() function reads all entries including special entries '.' (current directory) and '..' (parent directory). These are echoed with spaces.
  3. Final Answer:

    List of all files and folders inside 'myfolder' including '.' and '..' -> Option D
  4. Quick Check:

    readdir() lists all entries including '.' and '..' [OK]
Hint: readdir() returns '.' and '..' entries by default [OK]
Common Mistakes:
  • Assuming '.' and '..' are excluded automatically
  • Not checking if directory exists before reading
  • Forgetting to close directory handle
4. Consider this PHP code snippet:
$dir = 'testdir';
if (mkdir($dir)) {
  echo 'Created';
} else {
  echo 'Failed';
}
rmdir($dir);

What is the main issue if the directory testdir already exists?
medium
A. mkdir() will fail and echo 'Failed', and rmdir() will fail to remove the directory
B. mkdir() will fail and echo 'Failed', but rmdir() will still remove the directory
C. mkdir() will fail and echo 'Failed', and rmdir() will remove the directory anyway
D. mkdir() will overwrite the existing directory

Solution

  1. Step 1: Behavior of mkdir() when directory exists

    If testdir already exists, mkdir() returns false and echoes 'Failed'.
  2. Step 2: Behavior of rmdir() on existing directory

    Since the directory exists, rmdir() will attempt to remove it. If the directory is empty and permissions allow, it will succeed. Otherwise, it will fail.
  3. Final Answer:

    mkdir() will fail and echo 'Failed', but rmdir() will still remove the directory -> Option B
  4. Quick Check:

    mkdir() fails if exists; rmdir() removes empty directory [OK]
Hint: mkdir() fails if folder exists; rmdir() needs empty folder [OK]
Common Mistakes:
  • Assuming mkdir() overwrites existing folders
  • Expecting rmdir() to always succeed
  • Not checking if directory is empty before rmdir()
5. You want to list all files in a directory docs but skip the special entries . and ... Which PHP code snippet correctly does this?
hard
A. if (is_dir('docs')) { $dh = opendir('docs'); while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { echo $file . ' '; } } closedir($dh); }
B. if (is_dir('docs')) { $dh = opendir('docs'); while (($file = readdir($dh))) { echo $file . ' '; } closedir($dh); }
C. foreach (scandir('docs') as $file) { echo $file . ' '; }
D. if (is_dir('docs')) { $dh = opendir('docs'); while (($file = readdir($dh)) !== false) { echo $file . ' '; } closedir($dh); }

Solution

  1. Step 1: Understand how to skip '.' and '..'

    The special entries '.' and '..' appear in directory listings and must be explicitly skipped.
  2. Step 2: Analyze each code snippet

    if (is_dir('docs')) { $dh = opendir('docs'); while (($file = readdir($dh)) !== false) { if ($file != '.' && $file != '..') { echo $file . ' '; } } closedir($dh); } checks if the file is not '.' or '..' before echoing. foreach (scandir('docs') as $file) { echo $file . ' '; } uses scandir() but does not skip special entries.
  3. Final Answer:

    The snippet using if ($file != '.' && $file != '..') -> Option A
  4. Quick Check:

    Skip '.' and '..' with if check inside readdir() loop [OK]
Hint: Use if ($file != '.' && $file != '..') to skip special entries [OK]
Common Mistakes:
  • Not skipping '.' and '..' entries
  • Using scandir() without filtering special entries
  • Forgetting to check for false in readdir() loop
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard