Challenge - 5 Problems
File Writing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code writing to a file?
Consider this PHP code that writes text to a file. What will be the content of the file
example.txt after running this code?PHP
<?php $file = fopen('example.txt', 'w'); fwrite($file, "Hello"); fwrite($file, " World"); fclose($file); ?>
Attempts:
2 left
💡 Hint
Remember fwrite writes exactly what you give it without adding spaces.
✗ Incorrect
The fwrite function writes the exact string given. Since "Hello" and " World" are written separately, the file content is concatenated as "Hello World" without any extra characters. Note the space before 'World' is part of the string.
❓ Predict Output
intermediate2:00remaining
What does file_put_contents write to the file?
What will be the content of
data.txt after running this PHP code?PHP
<?php file_put_contents('data.txt', "Line1\nLine2"); ?>
Attempts:
2 left
💡 Hint
Check how PHP interprets escape sequences inside double quotes.
✗ Incorrect
Inside double quotes, \n is interpreted as a newline character. So the file will contain two lines: 'Line1' and 'Line2' on separate lines.
🔧 Debug
advanced2:00remaining
Why does this fwrite code cause an error?
This PHP code tries to write to a file but causes an error. What is the cause?
PHP
<?php $file = fopen('output.txt', 'r'); fwrite($file, "Test"); fclose($file); ?>
Attempts:
2 left
💡 Hint
Check the fopen mode and what it allows.
✗ Incorrect
Opening a file with mode 'r' means read-only. Writing with fwrite is not allowed and causes an error.
🧠 Conceptual
advanced2:00remaining
How does file_put_contents behave with FILE_APPEND flag?
What will be the content of
log.txt after running this PHP code twice in a row?PHP
<?php file_put_contents('log.txt', "Entry1\n"); file_put_contents('log.txt', "Entry2\n", FILE_APPEND); ?>
Attempts:
2 left
💡 Hint
FILE_APPEND adds content to the end of the file instead of overwriting.
✗ Incorrect
The first call writes 'Entry1\n' overwriting any existing content. The second call appends 'Entry2\n' to the file. So the file contains both entries in order.
❓ Predict Output
expert2:00remaining
What is the number of bytes written by fwrite here?
Given this PHP code, what is the value of
$bytes after fwrite runs?PHP
<?php $file = fopen('test.txt', 'w'); $bytes = fwrite($file, "Hello\nWorld"); fclose($file); echo $bytes; ?>
Attempts:
2 left
💡 Hint
Count all characters including the newline.
✗ Incorrect
The string "Hello\nWorld" has 11 characters: 5 letters in 'Hello', 1 newline, and 5 letters in 'World'. fwrite returns the number of bytes written, which is 11.