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 my-file.txt:

$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 fread and 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 fread called file_get_contents. To try it out, let‘s refactor our example to use the function:

$content = file_get_contents("my-file.txt");

This reads my-file.txt into $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 fwrite called file_put_contents. This allows us to write to a file with just one function call:

file_put_contents("hello.txt", "Hello, world!");

This opens 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_get_contents and file_put_contents to refactor a PHP script that uses fread and fwrite!



We have a program that reads read-me.txt into $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 file_put_contents instead.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?