Storing data in PHP files using PHP
Recommended With
In PHP, there are several ways to store structured data. While databases like MySQL are ideal for larger projects, for small projects or sensitive data like login credentials or config settings, a flat-file approach using PHP files can be more secure than using plain text formats like JSON or TXT.
This is because PHP files are executed by the server and do not expose their contents as plain text when accessed via the web. This makes them ideal for storing private configuration data.
This tutorial walks you through how to create, read, update, and delete data stored as arrays inside PHP files.
When to use PHP files
- - The data is sensitive (e.g., login credentials)
- - The data set is small and doesn't require complex queries
- - You want something easy to read and edit manually
Note: For non-sensitive or user-editable content, consider using a .json file instead. See the tutorial Storing data in JSON files using PHP for that.
Creating and saving data
Let's start with the basics: storing data as a PHP array into a file.
<?php
$filename = 'config.php';
// Data to be saved
$data = [
'db_user' => 'admin',
'db_pass' => 'secret123'
];
// Convert array to PHP code
$phpContent = "<?php\nreturn " . var_export($data, true) . ";\n";
// Save to file
file_put_contents($filename, $phpContent);
That's it. You've just saved structured data into a PHP 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 = 'config.php';
// Data to be saved
$data = [
'db_user' => 'admin',
'db_pass' => 'secret123'
];
$phpContent = "<?php\nreturn " . var_export($data, true) . ";\n";
// Check if the file exists and is writable
if (is_writable($filename) || !file_exists($filename)) {
$handle = fopen($filename, 'w');
if ($handle && flock($handle, LOCK_EX)) {
fwrite($handle, $phpContent);
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.
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.
Reading the data
To load and use the data from a PHP file, just include it. The file should return an array:
<?php
$config = include 'config.php';
// Output the values safely
echo 'DB User: ' . htmlspecialchars($config['db_user']) . "<br>";
echo 'DB Pass: ' . htmlspecialchars($config['db_pass']) . "<br>";
htmlspecialchars() ensures special characters are shown safely, preventing code injection and other malicious actions in the output.
Updating data
To update data, load the existing file, modify the array, and save it back:
<?php
$filename = 'config.php';
// Load the current data
$config = include $filename;
// Modify a value
$config['db_pass'] = 'newSecret456';
// Convert back to PHP code
$phpContent = "<?php\nreturn " . var_export($config, true) . ";\n";
// Save to file
if (is_writable($filename) || !file_exists($filename)) {
$handle = fopen($filename, 'w');
if ($handle && flock($handle, LOCK_EX)) {
fwrite($handle, $phpContent);
flock($handle, LOCK_UN);
fclose($handle);
} else {
echo "Unable to write to file.";
}
} else {
echo "File is not writable.";
}
This replaces just the password, and keeps the rest of the data intact.
Deleting data
You can either delete the file entirely using unlink(), or just remove specific keys from the array and overwrite the file.
<?php
$filename = 'config.php';
// Load the current data
$config = include $filename;
// Remove a key
unset($config['db_pass']);
// Convert to PHP code
$phpContent = "<?php\nreturn " . var_export($config, true) . ";\n";
// Save updated file
if (is_writable($filename) || !file_exists($filename)) {
$handle = fopen($filename, 'w');
if ($handle && flock($handle, LOCK_EX)) {
fwrite($handle, $phpContent);
flock($handle, LOCK_UN);
fclose($handle);
} else {
echo "Unable to write to file.";
}
} else {
echo "File is not writable.";
}
This safely removes just the db_pass key, keeping the rest intact.