The fwrite function writes data to an open file pointer. You must open the file first with fopen, then use fwrite to write content to it.
Click to reveal answer
beginner
How does file_put_contents simplify writing files compared to fwrite?
file_put_contents writes a string directly to a file without needing to open or close the file manually. It is a shortcut for simple file writing tasks.
Click to reveal answer
beginner
What must you do before using fwrite to write to a file?
You must open the file using fopen with the correct mode (like 'w' for write). After writing, you should close the file with fclose.
Click to reveal answer
intermediate
What happens if you use file_put_contents on a file that already exists?
By default, file_put_contents will overwrite the existing file content. You can append instead by passing the FILE_APPEND flag.
Click to reveal answer
beginner
Write a simple PHP code snippet using fwrite to write 'Hello' to a file named 'greet.txt'.
The file is opened in 'r' (read) mode, which does not allow writing.
Step 2: Understand fwrite requirements
Writing requires 'w', 'a', or 'r+' mode; 'r' mode causes error on fwrite.
Final Answer:
File opened in read mode, cannot write -> Option A
Quick Check:
Write needs write mode, not 'r' [OK]
Hint: Open file with 'w' or 'a' to write, not 'r' [OK]
Common Mistakes:
Using 'r' mode when writing
Ignoring file mode errors
Assuming fwrite works on read-only handle
5. You want to save user input lines into a file, but only if the input is not empty or whitespace. Which PHP code snippet correctly writes non-empty trimmed lines to "input.txt" using fwrite?
hard
A. $file = fopen('input.txt', 'w'); foreach ($lines as $line) { if (trim($line) !== '') { fwrite($file, $line . "\n"); } } fclose($file);
B. $file = fopen('input.txt', 'w'); foreach ($lines as $line) { fwrite($file, $line . "\n"); } fclose($file);
C. file_put_contents('input.txt', implode("\n", $lines));
D. $file = fopen('input.txt', 'r'); foreach ($lines as $line) { if ($line) { fwrite($file, $line); } } fclose($file);
Solution
Step 1: Check file open mode
$file = fopen('input.txt', 'w'); foreach ($lines as $line) { if (trim($line) !== '') { fwrite($file, $line . "\n"); } } fclose($file); opens file in 'w' mode, allowing writing and overwriting.
Step 2: Validate input filtering
It uses trim($line) !== '' to skip empty or whitespace-only lines before writing.
Step 3: Confirm writing and closing
Writes each valid line with newline and closes file properly.
Final Answer:
Option A code snippet -> Option A
Quick Check:
Trim check + fwrite + 'w' mode = correct [OK]
Hint: Trim input lines and write only non-empty with fwrite [OK]
Common Mistakes:
Not trimming lines before writing
Opening file in 'r' mode when writing
Using file_put_contents without filtering
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.