Challenge - 5 Problems
File Operations Mastery
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 file write and read code?
Consider the following PHP code that writes to a file and then reads from it. What will be printed?
PHP
<?php $file = 'test.txt'; file_put_contents($file, "Hello World!"); $content = file_get_contents($file); echo $content; ?>
Attempts:
2 left
💡 Hint
file_put_contents writes text to a file, file_get_contents reads it back.
✗ Incorrect
The code writes 'Hello World!' to 'test.txt' and then reads it back, printing the same text.
🧠 Conceptual
intermediate1:30remaining
Why is it important to close a file after opening it in PHP?
Which of the following best explains why closing a file after opening it is important?
Attempts:
2 left
💡 Hint
Think about what happens if too many files stay open.
✗ Incorrect
Closing a file releases system resources and flushes any buffered data to disk, preventing data loss.
🔧 Debug
advanced2:00remaining
What error does this PHP file open code produce?
Look at this PHP code snippet. What error will it cause when run if the file does not exist?
PHP
<?php $handle = fopen('nofile.txt', 'r'); ?>
Attempts:
2 left
💡 Hint
Opening a file for reading requires the file to exist.
✗ Incorrect
Trying to open a non-existent file for reading causes a warning because the file cannot be found.
📝 Syntax
advanced2:00remaining
Which option correctly appends text to a file in PHP?
You want to add text to the end of a file without deleting existing content. Which code snippet does this correctly?
Attempts:
2 left
💡 Hint
Appending means adding without removing old content.
✗ Incorrect
Using FILE_APPEND flag with file_put_contents adds text to the file end. Option D overwrites, C and D have syntax or logic errors.
🚀 Application
expert2:30remaining
How many lines will this PHP script write to the file?
This PHP script writes lines to a file inside a loop. How many lines will the file contain after running?
PHP
<?php $file = 'output.txt'; $handle = fopen($file, 'w'); for ($i = 1; $i <= 5; $i++) { fwrite($handle, "Line $i\n"); } fclose($handle); ?>
Attempts:
2 left
💡 Hint
Count how many times the loop runs and writes a line.
✗ Incorrect
The loop runs 5 times, writing one line each time, so the file will have 5 lines.