Unleash your creativity
🍂 Danny 1 week ago
it's (in)officially autumn season y'all! 🧡
Latest Additions Wish something
Danny
10.08.2026Danny
1 Design
nick
04.08.2026nick
Tool: Skinner, Tool: Split
Danny
30.07.2026Danny
1 Texture
nick
29.07.2026nick
Tool: Beautify
✏️ nick 18 hours ago
we're moving the tutorials from the tutorials subdomain to our main site, some things are still WIP! <3

Storing data in JSON files using PHP

Storing data in JSON files using PHP
Written by nick
25.05.2025

Requirements

PHP Version 7.0+

Recommended With

Recommended to read Creating simple files using PHP first to learn more about basic best practices when creating files using PHP.

1 Intro

In PHP, there are several ways to store structured data. While databases like MySQL are ideal for larger projects, for small projects or simple features, a flat-file approach using JSON can be much easier to manage.

This tutorial walks you through the basics of storing data in JSON files, including how to create, read, update, and delete data.

What is JSON?

JSON is a format for storing and exchanging data. PHP includes built-in functions to convert arrays and objects into JSON, and vice versa. This makes it perfect for flat-file storage.

When to use JSON files

  • - You don't need a full database system
  • - The data set is small and doesn't require complex queries
  • - You want something easy to read and edit manually

Important: JSON files are plain text. Never store passwords or sensitive data in them—especially if they're web-accessible. For config values or login credentials, use a .php file that returns an array instead. Read the tutorial Storing data in PHP files using PHP for that.

2 Creating and saving data

Let's start with the basics: storing data as an array into a JSON file.

<?php
$filename = 'data.json';

// Data to be saved
$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com'
];

// Convert data to JSON
$json = json_encode($data, JSON_PRETTY_PRINT);

// Save to file
file_put_contents($filename, $json);

That's it. You've just saved structured data into a JSON file! ✨ Now let's quickly make it safer by preventing issues when multiple users write to the file at the same time.

When multiple users might write to the file at the same time, use file locking (LOCK_EX) to avoid conflicts.

To make locking work, we can't use file_put_contents() anymore because it doesn't support locking by itself. So instead, we use fopen() to open the file manually, fwrite() to write the data, and flock() to apply the lock while writing.

<?php
$filename = 'data.json';
$data = [
    'name' => 'John Doe',
    'email' => 'john@example.com'
];

// Convert data to JSON
$json = json_encode($data, JSON_PRETTY_PRINT);

// Check if the file exists and is writeable
if (is_writable($filename) || !file_exists($filename)) {
    $handle = fopen($filename, 'w');

    if ($handle && flock($handle, LOCK_EX)) {
        fwrite($handle, $json);
        flock($handle, LOCK_UN);
        fclose($handle);
    } else {
        echo "Unable to write to file.";
    }
} else {
    echo "File is not writable.";
}

Also worth noting: we added a small but important check to see if the file exists and is writable before saving. It's a simple way to avoid file errors and make your code more reliable.

3 Useful modes for fopen()

When using fopen(), you can specify different file modes to control how the file is accessed—whether you're writing, appending, or reading and writing. Here are a few of the most common ones:

'w': Write (overwrites the file if it already exists)
'a': Append (adds content to the end)
'r+': Read and write (doesn't delete existing content)

Choose the mode based on what you're trying to do. For example, use 'a' if you're adding data to existing content, or 'w' if you're replacing everything in the file.

4 Reading the data

To load and use the data from a JSON file:

<?php
$filename = 'data.json';

// Check if the file exists
if (file_exists($filename)) {
    // Reads the JSON data
    $json = file_get_contents($filename);
    
    // Converts the data to a PHP array
    $data = json_decode($json, true);

    if (is_array($data)) {
        echo 'Name: ' . htmlspecialchars($data['name']) . "<br>";
        echo 'Email: ' . htmlspecialchars($data['email']) . "<br>";
    } else {
        echo "Data format is invalid.";
    }
} else {
    echo "File not found.";
}

htmlspecialchars() ensures special characters are shown safely, preventing code injection and other malicious actions in the output.

5 Updating data

To update data, load the existing JSON, change the PHP array, then save it back.

<?php
$filename = 'data.json';

// Check if the file exists
if (file_exists($filename)) {
    // Reads the JSON data
    $json = file_get_contents($filename);
    
    // Converts the data to a PHP array
    $data = json_decode($json, true);

    if (is_array($data)) {
    	// The new data
        $data['email'] = 'new@example.com';
        
        // Convert it back to JSON format
        $newJson = json_encode($data, JSON_PRETTY_PRINT);
        
        // Save to file
        file_put_contents($filename, $newJson);
    } else {
        echo "Data format is invalid.";
    }
} else {
    echo "File not found.";
}

This replaces the email but keeps the rest of the data intact.

6 Deleting data

You can delete the file entirely, or just remove specific keys from the JSON structure.

<?php
$filename = 'data.json';

// Check if the file exists
if (file_exists($filename)) {
    // Reads the JSON data
    $json = file_get_contents($filename);
    
    // Converts the data to a PHP array
    $data = json_decode($json, true);

    if (is_array($data)) {
        unset($data['email']); // Remove the email
        
        // Convert it back to JSON format
        $newJson = json_encode($data, JSON_PRETTY_PRINT);
        
        // Save to file
        file_put_contents($filename, $newJson);
    } else {
        echo "Data format is invalid.";
    }
} else {
    echo "File not found.";
}