0
0
PHPprogramming~10 mins

Reading files (fread, fgets, file) in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a file for reading.

PHP
<?php
$handle = fopen('example.txt', '[1]');
?>
Drag options to blanks, or click blank then click option'
Ax
Ba
Cr
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' which opens the file for writing and truncates it.
Using 'a' which opens the file for appending.
2fill in blank
medium

Complete the code to read 100 bytes from the file.

PHP
<?php
$handle = fopen('example.txt', 'r');
$content = fread($handle, [1]);
fclose($handle);
?>
Drag options to blanks, or click blank then click option'
A0
B100
C200
D50
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 which reads nothing.
Using a smaller number like 50 which reads less than needed.
3fill in blank
hard

Fix the error in the code to read one line from the file.

PHP
<?php
$handle = fopen('example.txt', 'r');
$line = [1]($handle);
fclose($handle);
?>
Drag options to blanks, or click blank then click option'
Afgets
Bfread
Cfile_get_contents
Dreadfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using fread which reads bytes, not lines.
Using file_get_contents which reads the whole file.
4fill in blank
hard

Fill both blanks to read the entire file into an array of lines and print the first line.

PHP
<?php
$lines = [1]('example.txt');
[2] $lines[0];
?>
Drag options to blanks, or click blank then click option'
Afile
Bprint_r
Cecho
Dfgets
Attempts:
3 left
💡 Hint
Common Mistakes
Using fgets instead of file to read all lines.
Using print_r which prints array structure, not just the line.
5fill in blank
hard

Fill all three blanks to open a file, read its entire content, and close it.

PHP
<?php
$handle = [1]('example.txt', 'r');
$content = [2]($handle, filesize('example.txt'));
fclose([3]);
?>
Drag options to blanks, or click blank then click option'
Afopen
Bfread
C$handle
Dfile_get_contents
Attempts:
3 left
💡 Hint
Common Mistakes
Using file_get_contents instead of fread when a handle is used.
Not closing the file handle.