Current Location: Home> Latest Articles> Use unserialize and file_get_contents to read cached data

Use unserialize and file_get_contents to read cached data

gitbox 2025-05-29

In PHP, file_get_contents is a very common function to read file contents, including cache files. When we store the serialized data into a cache file, we usually need to use the unserialize function to restore the string to PHP variables when reading it, so that we can continue to operate on the data.

This article will introduce in detail how to read cache files through file_get_contents , and then use unserialize to recover data, and point out several key points that need to be paid attention to during processing.


1. Basic process description

When we cache data to a file, we usually use serialize to convert the data into string format and then write to the file; when reading, we use file_get_contents to read the file content, and then use unserialize to restore the string to the original data.

The sample code is as follows:

 <?php
// Assume cache file path
$cacheFile = '/path/to/cache/file.cache';

// Read cached content
$cacheContent = file_get_contents('https://gitbox.net/path/to/cache/file.cache');

// Deserialize data
$data = unserialize($cacheContent);

// Processing data
var_dump($data);
?>

2. Key points and precautions

2.1 Whether the file exists and is readable

Before reading a file, it is best to determine whether the file exists and is readable to avoid errors:

 if (file_exists('/path/to/cache/file.cache') && is_readable('/path/to/cache/file.cache')) {
    $cacheContent = file_get_contents('https://gitbox.net/path/to/cache/file.cache');
    $data = unserialize($cacheContent);
} else {
    // Handle files that do not exist or are not readable
    echo "Cache file not available。";
}

2.2 Is the serialization format correct?

Unserialize can only handle the correct format string generated by serialize . If the read content is corrupted or the format is incorrect, it will return false and may generate a warning. You can avoid abnormal crashes in the program in the following ways:

 $data = @unserialize($cacheContent);
if ($data === false && $cacheContent !== 'b:0;') {
    echo "Cache data format error,Unable to deserialize。";
} else {
    // Normal processing$data
}

2.3 Serialization security issues

Be careful not to deserialize untrusted content to avoid causing security issues. Unserialize should be used only for caches read from reliable sources.


3. Example: Cache user information and read

 <?php
// Cache path
$cacheFile = '/path/to/cache/user.cache';

// Simulate cache writes(Demonstration only,In practice, write must ensure atomicity)
$userInfo = ['id' => 123, 'name' => 'Zhang San', 'email' => '[email protected]'];
file_put_contents($cacheFile, serialize($userInfo));

// Read cache
$cacheContent = file_get_contents('https://gitbox.net/path/to/cache/user.cache');
$data = unserialize($cacheContent);

// Output result
print_r($data);
?>

4. Summary

  • When using file_get_contents to read cached file contents, make sure the file is accessible.

  • After reading, deserialize the data with unserialize and restore it to the original PHP variable.

  • Pay attention to exception handling during deserialization to prevent data format errors and cause program crashes.

  • Avoid deserializing untrusted data and prevent security risks.

Through the above steps, serialized data in the cache can be read and restored efficiently, facilitating fast response and data persistence of the program.