Bird
0
0

You want to write PHP code that lists all files in a directory 'uploads' and prints their sizes only if they are readable files. Which code snippet correctly does this?

hard📝 Application Q9 of 15
PHP - File Handling
You want to write PHP code that lists all files in a directory 'uploads' and prints their sizes only if they are readable files. Which code snippet correctly does this?
A$files = scandir('uploads'); foreach ($files as $file) { echo filesize($file); }
B$files = scandir('uploads'); foreach ($files as $file) { if (is_dir($file)) { echo $file . " is a directory\n"; } }
C$files = scandir('uploads'); foreach ($files as $file) { if (is_file('uploads/' . $file) && is_readable('uploads/' . $file)) { echo $file . ': ' . filesize('uploads/' . $file) . " bytes\n"; } }
D$files = scandir('uploads'); foreach ($files as $file) { if (file_exists($file)) { echo $file; } }
Step-by-Step Solution
Solution:
  1. Step 1: Use scandir() to get files in 'uploads'

    scandir('uploads') returns an array of filenames in the directory.
  2. Step 2: Check each item is a file and readable

    Use is_file() and is_readable() with full path 'uploads/' . $file to ensure correct checks.
  3. Step 3: Print filename and filesize

    Use echo to print filename and filesize with proper concatenation and newline.
  4. Final Answer:

    Code snippet C correctly lists readable files with sizes -> Option C
  5. Quick Check:

    Combine scandir, is_file, is_readable, filesize with full path [OK]
Quick Trick: Use full path with is_file and filesize in loops [OK]
Common Mistakes:
  • Not using full path for checks
  • Checking directories instead of files
  • Ignoring readability before filesize

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes