0
0
PHPprogramming~20 mins

Writing files (fwrite, file_put_contents) in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Writing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
?>
AThe file contains: Hello\nWorld
BThe file contains: HelloWorld
CThe file contains: Hello World
DThe file is empty
Attempts:
2 left
💡 Hint
Remember fwrite writes exactly what you give it without adding spaces.
Predict Output
intermediate
2: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");
?>
A
Line1
Line2
BLine1 Line2
CLine1\nLine2
DAn empty file
Attempts:
2 left
💡 Hint
Check how PHP interprets escape sequences inside double quotes.
🔧 Debug
advanced
2: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);
?>
Afclose must be called before fwrite
BThe file 'output.txt' does not exist, causing fwrite to fail
Cfwrite requires the file to be opened in binary mode
Dfopen mode 'r' opens file for reading only, so fwrite fails
Attempts:
2 left
💡 Hint
Check the fopen mode and what it allows.
🧠 Conceptual
advanced
2: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);
?>
A
Entry1
Entry2
B
Entry1
Entry1
Entry2
C
Entry1
D
Entry2
Attempts:
2 left
💡 Hint
FILE_APPEND adds content to the end of the file instead of overwriting.
Predict Output
expert
2: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;
?>
A12
B11
C10
D5
Attempts:
2 left
💡 Hint
Count all characters including the newline.