Bird
0
0

How can you append text to a file safely in PHP while ensuring the file is closed properly?

hard📝 Application Q9 of 15
PHP - File Handling
How can you append text to a file safely in PHP while ensuring the file is closed properly?
Afile_put_contents('file.txt', 'More text');
B$file = fopen('file.txt', 'a'); fwrite($file, 'More text'); fclose($file);
Cfwrite('file.txt', 'More text'); fclose('file.txt');
D$file = fopen('file.txt', 'w'); fwrite($file, 'More text'); fclose($file);
Step-by-Step Solution
Solution:
  1. Step 1: Understand file open modes

    'a' mode opens file for appending, preserving existing content.
  2. Step 2: Check fwrite and fclose usage

    fwrite writes to opened file handle, fclose closes it properly.
  3. Final Answer:

    $file = fopen('file.txt', 'a'); fwrite($file, 'More text'); fclose($file); -> Option B
  4. Quick Check:

    Use fopen with 'a' and fclose for safe append [OK]
Quick Trick: Use fopen('file', 'a') to append safely [OK]
Common Mistakes:
  • Using 'w' mode overwrites file
  • Passing filename to fwrite
  • Not closing file after writing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes