Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file for reading.
PHP
<?php $file = fopen('example.txt', '[1]'); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which opens the file for writing and erases content.
✗ Incorrect
The mode 'r' opens the file for reading only.
2fill in blank
mediumComplete the code to write 'Hello' to a file.
PHP
<?php $file = fopen('greeting.txt', 'w'); fwrite([1], 'Hello'); fclose($file); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable not defined or different from the fopen result.
✗ Incorrect
The variable $file holds the file resource returned by fopen, which is used by fwrite.
3fill in blank
hardFix the error in the code to read a file line by line.
PHP
<?php $file = fopen('data.txt', 'r'); while (($line = fgets([1])) !== false) { echo $line; } fclose($file); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable not assigned or undefined in the code.
✗ Incorrect
The variable $file is the file pointer used with fgets to read lines.
4fill in blank
hardFill both blanks to check if a file exists and then delete it.
PHP
<?php if ([1]('temp.txt')) { [2]('temp.txt'); } ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using fopen instead of file_exists for checking file presence.
✗ Incorrect
Use file_exists to check if the file is there, and unlink to delete it.
5fill in blank
hardFill all three blanks to open a file, write text, and close it properly.
PHP
<?php [1] = fopen('log.txt', '[2]'); fwrite([3], "Log entry\n"); fclose($file); ?>
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' mode erases file content instead of appending.
✗ Incorrect
Assign fopen to $file, open in append mode 'a', and write using $file.