0
0
PHPprogramming~10 mins

Writing files (fwrite, file_put_contents) 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 writing.

PHP
<?php
$file = fopen('example.txt', '[1]');
?>
Drag options to blanks, or click blank then click option'
Aw
Bx
Ca
Dr
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' which opens the file for reading only.
Using 'a' which appends instead of overwriting.
2fill in blank
medium

Complete the code to write the string 'Hello World' to the file using fwrite.

PHP
<?php
$file = fopen('example.txt', 'w');
fwrite([1], 'Hello World');
fclose($file);
?>
Drag options to blanks, or click blank then click option'
A$fp
B$filename
C$handle
D$file
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable that does not hold the file handle.
Using the filename string instead of the file handle.
3fill in blank
hard

Fix the error in the code to write 'Data' to a file using file_put_contents.

PHP
<?php
[1]('data.txt', 'Data');
?>
Drag options to blanks, or click blank then click option'
Afile_put_contents
Bfile_write
Cwrite_file
Dput_file_contents
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent functions like file_write or write_file.
Mixing up the function name order.
4fill in blank
hard

Fill both blanks to write 'Hello' to 'greeting.txt' and then close the file.

PHP
<?php
$file = fopen('greeting.txt', '[1]');
fwrite($file, '[2]');
fclose($file);
?>
Drag options to blanks, or click blank then click option'
Aw
Br
CHello
DWorld
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'r' mode which is read-only.
Writing the wrong string like 'World'.
5fill in blank
hard

Fill all three blanks to write the uppercase filename, the content variable, and the comparison operator in the code.

PHP
<?php
$filename = 'log.txt';
$content = 'Log entry';
if (strlen($content) [3] 0) {
    file_put_contents([1], [2]);
}
?>
Drag options to blanks, or click blank then click option'
A$filename
B$content
C>
DLOG.TXT
Attempts:
3 left
💡 Hint
Common Mistakes
Using the uppercase string 'LOG.TXT' instead of the variable.
Using '<' instead of '>' in the condition.