Skip to content

PHP Tutorial File Handling

file_get_contents() and file_put_contents()

Lesson 168 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

For small files, these two functions replace the whole open-read-close routine.

file_put_contents(): write a file

index.php
PHP
<?php
file_put_contents("hello.txt", "Hello, world!");

echo file_get_contents("hello.txt");
Output
OUTPUT
Hello, world!

It creates the file if needed, replaces the content, and returns the number of bytes written (or false on failure).

index.php
PHP
<?php
$bytes = file_put_contents("short.txt", "abc");

var_dump($bytes);
Output
OUTPUT
int(3)

file_get_contents(): read a file

It returns the whole file as a string, or false if the file cannot be read.

index.php
PHP
<?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);
}
Output
OUTPUT
WELCOME

Flags

FlagMeaning
FILE_APPENDAdd to the end instead of replacing
LOCK_EXLock the file while writing
index.php
PHP
<?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")), ",");
Output
OUTPUT
1,2

Write an array

If the second argument is an array, PHP joins the items.

index.php
PHP
<?php
file_put_contents("list.txt", ["a\n", "b\n", "c\n"]);

echo count(file("list.txt"));
Output
OUTPUT
3

Read part of a file

index.php
PHP
<?php
file_put_contents("long.txt", "0123456789");

echo file_get_contents("long.txt", false, null, 2, 4);
Output
OUTPUT
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)

index.php
PHP
<?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");
Output
OUTPUT
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).

lightbulb
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.