0
0
PHPprogramming~20 mins

Reading files (fread, fgets, file) in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Reading 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 using fread?

Consider this PHP code that reads from a file named example.txt containing the text Hello World!:

$file = fopen('example.txt', 'r');
$content = fread($file, 5);
fclose($file);
echo $content;

What will be printed?

PHP
$file = fopen('example.txt', 'r');
$content = fread($file, 5);
fclose($file);
echo $content;
AHello World
BHello World!
CHello
DWorld
Attempts:
2 left
💡 Hint

Remember, fread reads a specific number of bytes from the file.

Predict Output
intermediate
2:00remaining
What does fgets() return when reading a file line?

Given a file data.txt with the content:

Line one
Line two
Line three

What will this PHP code output?

$file = fopen('data.txt', 'r');
$line = fgets($file);
fclose($file);
echo $line;
PHP
$file = fopen('data.txt', 'r');
$line = fgets($file);
fclose($file);
echo $line;
ALine one
BLine one\n
CLine one\r\n
DLine one\nLine two
Attempts:
2 left
💡 Hint

Check if fgets includes the newline character at the end of the line.

Predict Output
advanced
2:00remaining
What is the output of reading a file with file() function?

Assume notes.txt contains:

First line
Second line
Third line

What will this PHP code output?

$lines = file('notes.txt');
echo count($lines);
PHP
$lines = file('notes.txt');
echo count($lines);
A3
B1
C0
DError
Attempts:
2 left
💡 Hint

The file() function reads the file into an array, one element per line.

Predict Output
advanced
2:00remaining
What error does this PHP code raise when reading a non-existent file?

What happens when running this PHP code?

$file = fopen('missing.txt', 'r');
fgets($file);
PHP
$file = fopen('missing.txt', 'r');
fgets($file);
AWarning: fopen(): failed to open stream: No such file or directory
BFatal error: Call to undefined function fopen()
CNULL
DEmpty string
Attempts:
2 left
💡 Hint

Check what happens if you try to open a file that does not exist in read mode.

🧠 Conceptual
expert
3:00remaining
Which option correctly reads the entire file content into a string?

You want to read the entire content of story.txt into a single string variable in PHP. Which code snippet does this correctly?

A
$file = fopen('story.txt', 'r');
$content = '';
while (!feof($file)) {
  $content .= fgets($file);
}
fclose($file);
echo $content;
B
$content = file('story.txt');
echo $content;
C
$content = fread('story.txt');
echo $content;
D
$content = file_get_contents('story.txt');
echo $content;
Attempts:
2 left
💡 Hint

Look for the function that reads the whole file as a string in one call.