Bird
0
0

How can you safely delete a directory temp and all its contents (files and subdirectories) in PHP?

hard📝 Application Q9 of 15
PHP - File Handling
How can you safely delete a directory temp and all its contents (files and subdirectories) in PHP?
AUse rmdir('temp') directly to delete everything
BUse scandir() and ignore deleting files, just remove directory
CUse unlink('temp') to delete the directory and contents
DWrite a recursive function to delete all files and subdirectories, then remove the directory
Step-by-Step Solution
Solution:
  1. Step 1: Understand rmdir() and unlink() limitations

    rmdir() only removes empty directories; unlink() deletes files, not directories.
  2. Step 2: Use recursion to delete contents first

    To delete all contents safely, recursively delete files and subdirectories before removing the directory.
  3. Final Answer:

    Write a recursive function to delete all files and subdirectories, then remove the directory -> Option D
  4. Quick Check:

    Recursive delete needed for non-empty directories [OK]
Quick Trick: Delete directory contents recursively before rmdir() [OK]
Common Mistakes:
  • Trying rmdir() on non-empty directory
  • Using unlink() on directories
  • Ignoring subdirectories when deleting

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes