Nice work! We can now read and write files in PHP. However, you might’ve noticed that most operations, including both reading and writing, can take quite a few steps. For example, here’s what it takes to read a file called
$name = "my-file.txt"; $file = fopen($name, "r"); $size = filesize($name); $content = fread($file, $size); fclose($file);
Wouldn’t it be nice if there was an easier way? Luckily, there is! PHP offers shorthand alternatives to
fwrite that take care of implementation details like opening the file and obtaining its size.
First, let’s take a look at an alternative to
file_get_contents. To try it out, let‘s refactor our example to use the function:
$content = file_get_contents("my-file.txt");
$content, just as we did before — but with a fraction of the code. We only need one argument (the file name) and PHP takes care of the rest.
Likewise, PHP includes an alternative to
file_put_contents. This allows us to write to a file with just one function call:
file_put_contents("hello.txt", "Hello, world!");
hello.txt in write mode, writes “Hello, world!” to the file, and closes the file in one function call. Since the file is opened in write mode, any existing content will be erased from the file. However, if we’d like to append to the file instead, we can specify this by passing
FILE_APPEND as the third argument:
file_put_contents("cool-pets.txt", "Bailey", FILE_APPEND);
To let us customize its behavior, the
file_put_contents function takes an optional third argument that can be set to one of a few values, including
FILE_APPEND. These values, called flags, are constants included in the PHP language.
Now, let’s use
file_put_contents to refactor a PHP script that uses
We have a program that reads
$read_text. Refactor this part of the application to use
file_get_contents. Don’t forget to remove the old code.
The program also appends “I love PHP!” to
append-me.txt. Refactor this part of the application to use