For small files, these two functions replace the whole open-read-close routine.
file_put_contents(): write a file
<?php
file_put_contents("hello.txt", "Hello, world!");
echo file_get_contents("hello.txt");
Hello, world!
It creates the file if needed, replaces the content, and returns the number of bytes written (or false on failure).
<?php
$bytes = file_put_contents("short.txt", "abc");
var_dump($bytes);
int(3)
file_get_contents(): read a file
It returns the whole file as a string, or false if the file cannot be read.
<?php
file_put_contents("greeting.txt", "Welcome");
$text = file_get_contents("greeting.txt");
if ($text === false) {
echo "Could not read the file";
} else {
echo strtoupper($text);
}
WELCOME
Flags
| Flag | Meaning |
|---|---|
FILE_APPEND | Add to the end instead of replacing |
LOCK_EX | Lock the file while writing |
<?php
file_put_contents("counter.txt", "1\n");
file_put_contents("counter.txt", "2\n", FILE_APPEND | LOCK_EX);
echo trim(str_replace("\n", ",", file_get_contents("counter.txt")), ",");
1,2
Write an array
If the second argument is an array, PHP joins the items.
<?php
file_put_contents("list.txt", ["a\n", "b\n", "c\n"]);
echo count(file("list.txt"));
3
Read part of a file
<?php
file_put_contents("long.txt", "0123456789");
echo file_get_contents("long.txt", false, null, 2, 4);
2345
The last two arguments are the starting position and the length.
Reading a URL
file_get_contents("https://...") can read a web page or an API, if allow_url_fopen is on. For anything serious, use cURL, which gives you timeouts, headers and error handling. See cURL Basics.
A simple counter (and why it is not safe)
<?php
file_put_contents("hits.txt", "0");
$hits = (int) file_get_contents("hits.txt");
file_put_contents("hits.txt", (string) ($hits + 1));
echo file_get_contents("hits.txt");
1
Two visitors at the same moment could both read 0 and both write 1. For counters that matter, use a database, which handles this properly.
Memory
Both functions use memory for the whole file. A 500 MB file will use 500 MB of memory. For large files, read in pieces (Reading Files).
JSON config in one line
json_decode(file_get_contents("config.json"), true) loads a JSON settings file into an array. Working with JSON Data covers it.