Bird
0
0

Identify the error in this PHP code snippet for writing to a file:

medium📝 Debug Q14 of 15
PHP - File Handling
Identify the error in this PHP code snippet for writing to a file:
$file = fopen('data.txt', 'r');
fwrite($file, 'Sample text');
fclose($file);
Afwrite() function is misspelled.
BUsing 'r' mode prevents writing to the file.
Cfclose() should be called before fwrite().
DThe filename must be an absolute path.
Step-by-Step Solution
Solution:
  1. Step 1: Check file open mode

    The file is opened with mode 'r' which is read-only and does not allow writing.
  2. Step 2: Understand fwrite() requirements

    To write, the file must be opened with 'w', 'a', or 'r+' modes. Using 'r' causes an error on fwrite.
  3. Final Answer:

    Using 'r' mode prevents writing to the file. -> Option B
  4. Quick Check:

    Write needs 'w' or 'a' mode, not 'r' [OK]
Quick Trick: Open file with write mode to use fwrite() [OK]
Common Mistakes:
  • Opening file in read mode but trying to write
  • Calling fclose before fwrite
  • Thinking filename must be absolute path

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes