0
0
PHPprogramming~20 mins

File open modes in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
File Open Modes 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 when opening a file in 'r' mode?
Consider the following PHP code snippet. What will it output if the file 'example.txt' exists and contains the text 'Hello World'?
PHP
<?php
$handle = fopen('example.txt', 'r');
$content = fread($handle, 5);
echo $content;
fclose($handle);
?>
AWorld
BError: Cannot open file
CHello World
DHello
Attempts:
2 left
💡 Hint
The 'r' mode opens the file for reading from the beginning.
Predict Output
intermediate
2:00remaining
What happens when opening a non-existent file in 'r' mode?
What will the following PHP code output if 'nofile.txt' does not exist?
PHP
<?php
$handle = fopen('nofile.txt', 'r');
if (!$handle) {
    echo 'Failed to open file';
} else {
    echo 'File opened';
}
?>
AFile opened
BFailed to open file
CWarning: fopen(): failed to open stream: No such file or directory
DEmpty output
Attempts:
2 left
💡 Hint
The 'r' mode requires the file to exist.
Predict Output
advanced
2:00remaining
What is the output when writing to a file opened in 'w' mode?
Given the file 'data.txt' contains 'Old Data', what will be the content of the file after running this PHP code?
PHP
<?php
$handle = fopen('data.txt', 'w');
fwrite($handle, 'New Data');
fclose($handle);
$contents = file_get_contents('data.txt');
echo $contents;
?>
ANew Data
BError: Cannot write to file
COld DataNew Data
DOld Data
Attempts:
2 left
💡 Hint
The 'w' mode truncates the file before writing.
Predict Output
advanced
2:00remaining
What will be the output when appending to a file with 'a' mode?
If 'log.txt' initially contains 'Line1\n', what will be the content after running this PHP code?
PHP
<?php
$handle = fopen('log.txt', 'a');
fwrite($handle, 'Line2\n');
fclose($handle);
$contents = file_get_contents('log.txt');
echo $contents;
?>
A
Line1
Line2
B
Line2
CLine1
DError: Cannot append to file
Attempts:
2 left
💡 Hint
The 'a' mode adds data to the end of the file without deleting existing content.
🧠 Conceptual
expert
2:00remaining
Which file open mode allows reading and writing without truncating the file?
In PHP, which file open mode lets you read and write to a file without deleting its existing content at open?
A'x+'
B'w+'
C'r+'
D'a+'
Attempts:
2 left
💡 Hint
One mode opens the file for reading and writing but does not clear it.