Bird
Raised Fist0
PHPprogramming~10 mins

Writing files (fwrite, file_put_contents) in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Writing files (fwrite, file_put_contents)
Open file with fopen or use file_put_contents
↓
Write data to file
↓
Check if write succeeded
↓
Close file if fopen used
↓
End
This flow shows how PHP writes data to a file using fopen/fwrite or file_put_contents, then closes the file if needed.
Execution Sample
PHP
<?php
$file = fopen('test.txt', 'w');
fwrite($file, "Hello\n");
fclose($file);
?>
This code opens a file for writing, writes 'Hello' with a newline, then closes the file.
Execution Table
StepActionFunction CallResultFile State
1Open file for writingfopen('test.txt', 'w')File handle resourceFile opened, empty content
2Write string to filefwrite(file handle, "Hello\n")6 bytes writtenFile contains 'Hello\n'
3Close filefclose(file handle)trueFile closed, content saved
4End--File closed, content saved
💡 File closed after writing, data saved to 'test.txt'
Variable Tracker
VariableStartAfter fopenAfter fwriteAfter fclose
$filenullresource (file handle)resource (file handle)null
Key Moments - 3 Insights
Why do we need to close the file after writing?
Closing the file with fclose ensures all data is saved and resources are freed, as shown in step 3 of the execution_table.
What happens if fopen fails to open the file?
If fopen fails, it returns false instead of a resource. You should check this before calling fwrite to avoid errors.
How is file_put_contents different from fopen/fwrite?
file_put_contents combines opening, writing, and closing in one call, simplifying the process as it handles all steps internally.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the file state after step 2?
AFile is closed and empty
BFile is open and contains 'Hello\n'
CFile is open but empty
DFile is closed and contains 'Hello\n'
💡 Hint
Check the 'File State' column in row for step 2 in execution_table
At which step is the file handle resource no longer available?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look at variable_tracker for $file after fclose in step 4
If we replace fopen/fwrite/fclose with file_put_contents, how many steps in execution_table would be combined?
A3 steps
B2 steps
C1 step
D4 steps
💡 Hint
file_put_contents does opening, writing, and closing in one call, combining steps 1, 2, and 3
Concept Snapshot
PHP file writing:
- fopen('file', 'w') opens file for writing
- fwrite(handle, data) writes data
- fclose(handle) closes file
- file_put_contents('file', data) does all in one
Always close files to save data and free resources.
Full Transcript
This lesson shows how PHP writes data to files using fopen, fwrite, and fclose functions, or the simpler file_put_contents function. First, fopen opens the file and returns a handle. Then fwrite writes the string data to the file. Finally, fclose closes the file to save changes. Alternatively, file_put_contents does all these steps in one call. Closing the file is important to ensure data is saved and resources are freed. The execution table traces each step and the file's state. The variable tracker shows how the file handle changes from null to resource and back to null after closing. Key moments clarify why closing is needed, what happens if fopen fails, and how file_put_contents simplifies writing. The quiz tests understanding of file state after writing, when the handle is closed, and how steps combine with file_put_contents.

Practice

(1/5)
1. Which PHP function is best for quickly writing a string to a file without manually opening or closing it?
easy
A. fclose
B. fwrite
C. fopen
D. file_put_contents

Solution

  1. Step 1: Understand the purpose of file_put_contents

    This function writes data to a file in one step, handling opening and closing automatically.
  2. Step 2: Compare with fwrite

    fwrite requires manual file opening and closing, so it's not as quick for simple writes.
  3. Final Answer:

    file_put_contents -> Option D
  4. Quick Check:

    Quick file write = file_put_contents [OK]
Hint: Use file_put_contents for quick file writes without fopen/fclose [OK]
Common Mistakes:
  • Confusing fwrite as a standalone write function
  • Thinking fopen writes data
  • Assuming fclose writes data
2. Which of the following is the correct syntax to write "Hello" to a file named "greet.txt" using fwrite?
easy
A. $file = fopen('greet.txt'); fwrite($file, 'Hello');
B. $file = fopen('greet.txt', 'w'); fwrite($file, 'Hello'); fclose($file);
C. file_put_contents('greet.txt', 'Hello');
D. fwrite('greet.txt', 'Hello');

Solution

  1. Step 1: Check the correct usage of fwrite

    fwrite requires a file handle from fopen opened in write mode.
  2. Step 2: Validate the full sequence

    $file = fopen('greet.txt', 'w'); fwrite($file, 'Hello'); fclose($file); opens the file in write mode, writes "Hello", then closes the file properly.
  3. Final Answer:

    $file = fopen('greet.txt', 'w'); fwrite($file, 'Hello'); fclose($file); -> Option B
  4. Quick Check:

    fopen + fwrite + fclose = correct syntax [OK]
Hint: Always fopen with 'w' before fwrite, then fclose [OK]
Common Mistakes:
  • Calling fwrite without fopen file handle
  • Missing file mode in fopen
  • Not closing the file after writing
3. What will be the output of this PHP code?
$filename = 'data.txt';
file_put_contents($filename, "Line1\n");
$file = fopen($filename, 'a');
fwrite($file, "Line2\n");
fclose($file);
echo file_get_contents($filename);
medium
A. Line2
B. Line1
C. Line1 Line2
D. Error: file not found

Solution

  1. Step 1: Analyze file_put_contents call

    This writes "Line1\n" to 'data.txt', creating or overwriting the file.
  2. Step 2: Analyze fopen with 'a' mode and fwrite

    Opening in append mode adds "Line2\n" after existing content.
  3. Step 3: Read file content with file_get_contents

    It returns both lines concatenated with newlines.
  4. Final Answer:

    Line1 Line2 -> Option C
  5. Quick Check:

    Append mode adds lines, so both lines appear [OK]
Hint: file_put_contents overwrites; fopen 'a' appends [OK]
Common Mistakes:
  • Assuming file_put_contents appends instead of overwrites
  • Forgetting 'a' mode appends
  • Expecting only last line output
4. Identify the error in this PHP code snippet that tries to write "Test" to "file.txt":
$file = fopen('file.txt', 'r');
fwrite($file, 'Test');
fclose($file);
medium
A. File opened in read mode, cannot write
B. Missing semicolon after fwrite
C. fclose called before fwrite
D. fopen filename missing extension

Solution

  1. Step 1: Check fopen mode

    The file is opened in 'r' (read) mode, which does not allow writing.
  2. Step 2: Understand fwrite requirements

    Writing requires 'w', 'a', or 'r+' mode; 'r' mode causes error on fwrite.
  3. Final Answer:

    File opened in read mode, cannot write -> Option A
  4. 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

  1. 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.
  2. Step 2: Validate input filtering

    It uses trim($line) !== '' to skip empty or whitespace-only lines before writing.
  3. Step 3: Confirm writing and closing

    Writes each valid line with newline and closes file properly.
  4. Final Answer:

    Option A code snippet -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard