WeCodeAcademy

PHP File Handling

ExamplePHP
<?php
$path = sys_get_temp_dir() . "/wecode_demo.txt";

file_put_contents($path, "line one\nline two\n");
file_put_contents($path, "line three\n", FILE_APPEND);

echo file_get_contents($path);
$lines = file($path, FILE_IGNORE_NEW_LINES);
echo count($lines), " lines\n";

$f = fopen($path, "r");
while (($line = fgets($f)) !== false) {
  echo strtoupper($line);
}
fclose($f);

echo file_exists($path) ? "exists" : "missing", "\n";
unlink($path);
echo file_exists($path) ? "exists" : "deleted", "\n";
Output
line one
line two
line three
3 lines
LINE ONE
LINE TWO
LINE THREE
exists
deleted
Quick check

Which function reads a whole file into a string?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.